Home > Enterprise >  Use custom Javascript files with imports in Angular
Use custom Javascript files with imports in Angular

Time:02-15

I am using Angular 12 and I wanted to use custom JavaScript files in one of my ts components. To get this working I understood I need to add my custom.js file to the "Scripts" section in the angular.json and declare this in my ts component:

My custom.js file

function test() {
      alert("Hello!");

}

In the app.component.ts

import { Component, OnInit } from "@angular/core";
import { Subject, Observable } from "rxjs";
declare function test(): void;

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"],
})
export class AppComponent implements OnInit {
....
...
test();

and in the angular.json file i added the path to my custom.js

.....
   "scripts": [
              "src/assets/js/custom.js"]
.....

This works fine and the alert message is displayed correctly when de app is served.

Let say now I want to use some Javascript library in my custom.js file, for example "sharp":

import {sharp} from "sharp";

function test() {
  alert("Hello!");
  const image = sharp("file.jpg");
}

Now when I serve the app via the "ng s", I can see the following error in the console of my browser:

Cannot use import statement outside a module

This points to the "import {sharp} from "sharp"" line of my custom.js file of course.

I have alreayd tried to:

  • add "type":"module" in the package.json but it did not solve the problem.
  • install the sharp dependency via "npm i --save @types/sharp", but it did not help.
  • add a "module.exoprts" in the custom.js file, but this also did not help.

My question is then the following:

where and how in my Angular project should I declare the need/use of the sharp library in order to let my custom.js work?

Thanks

CodePudding user response:

To import another js file into another js sharp.js should export function sharp() and test.js should import { sharp } from './main.js';. Then test can use sharp() and your Angulr project is only using declared function test(). https://www.tutorialrepublic.com/faq/how-to-include-a-javascript-file-in-another-javascript-file.php

CodePudding user response:

First, export the function test.

export function test() {
  alert('custom js');
}

Import it into your app.component.

import {Component} from '@angular/core';
import * as yourlib from 'src/custom.js';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

 constructor(){
   yourlib.test();
}
}

  • Related