A2oz

How to Import JavaScript File in Angular Project?

Published in Angular 2 mins read

You can import JavaScript files into your Angular project using the import statement. This statement allows you to import functions, classes, and other variables from external JavaScript files.

Using the import statement

  1. Create a JavaScript file: Create a new JavaScript file (e.g., my-utils.js) and place it in your src/assets folder.

  2. Define your code: Write your functions, classes, or variables in this file.

  3. Import the file: In your Angular component or service, import the file using the import statement:

    import * as myUtils from './assets/my-utils.js';
    • The * as myUtils syntax imports all the exported members from the file and assigns them to the myUtils variable.

    • You can then access the imported functions, classes, and variables using the myUtils object:

      console.log(myUtils.myFunction());

Using script tag in angular.json

Alternatively, you can include JavaScript files using the script tag in your angular.json file. This method is useful for external libraries that don't have TypeScript definitions.

  1. Add the script tag: Add the following line to the scripts array within the projects/your-project/architect/build/options section of your angular.json file:

    "scripts": [
      "src/assets/my-utils.js"
    ]
  2. Access the code: Once you've added the script tag, the JavaScript code in your file will be available globally. You can access the functions and variables directly:

    console.log(myFunction());

Considerations

  • TypeScript definitions: If you're using TypeScript, it's recommended to provide a TypeScript definition file (.d.ts) for your JavaScript file to ensure type safety and better code completion.
  • Module loading: If your JavaScript file exports a module, you can import it directly using the module's name instead of the * as syntax.

Example

my-utils.js:

function myFunction() {
  return "Hello from my-utils.js!";
}

export { myFunction };

app.component.ts:

import { Component } from '@angular/core';
import { myFunction } from './assets/my-utils.js'; // Import the function

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  message = myFunction(); // Call the imported function
}

Output:

Hello from my-utils.js!

Related Articles