Angular Code Example: Utilizing TypeScript File in JavaScript Environment

To create entries in the package.json, use the following format and execute it through the command line. If you’d like a detailed guide with a typescript file example, check out this article on passing environment variables with env files in Angular. If you prefer to use variables during build time, consider using dotenv. To do so, simply require and configure dotenv as early as possible in your application, and create a .env file in your project’s root directory. Another option is to create a config file during run-time. To do so, create a file named app-config.json in the assets folder with your desired variables, create a service called AppConfigService to read the file, and voila!

Solution 1:

It’s possible to utilize JavaScript within an Angular application.

To begin, generate a file named “demo.js” within the directory “assets/javascript”.

export function test1(){
    console.log('Calling test 1 function');

The second step is to generate a file named “demo.d.ts” in the directory “assets/javascript”.

export declare function test1();

Step 3. Use it in your component

import { test1 } from '../assets/javascript/demo'; 
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  constructor() {

It is important to ensure that the names of both the .js and .d.ts files match.

Solution 2:

To avoid script errors, switch the order in which you load your JavaScript files. Load




. This will ensure that the function your script tries to access is from a loaded file. Simply swapping those two lines of code should do the trick.


Frequently Asked Questions