Amith Dissanayaka
Amith Dissanayaka

Reputation: 1059

import external js into only one component

When I import external js into angular 4 one component, In every component it will load. How can I import that js file into only one component and how load it when only function call.

//custom component
import * as extjs from '../assets/extjs.js';

constructor(){
this.myfunction();
}


myfunction(){
extjs.extfunc();
}

Upvotes: 0

Views: 259

Answers (2)

Radonirina Maminiaina
Radonirina Maminiaina

Reputation: 7004

The reason is when you import your module, it will be injected directly into the app.js file of angular. So, all module can use it. For instance, when you do this to another component:

declare var extjs: any;
console.log(extjs);

Your extjs return exts api.

So I recommand you to use dynamic import, so your extjs will be ejected only when the component need to use it.

How to do it?

In the file tsconfig.app.json into your folder src, change the following line:

"module": "es2015"

With this line:

"module": "esnext"

It will allow you to make lazy loading script.

So in your component, just do this:

constructor(){
   this.myfunction();
}


async myfunction(){
  const extjs = await import('../assets/extjs.js');
  extjs.extfunc();
}

Check your network tab into your dev tool, load this component or inject it into another component and you will see the chunk of extjs is generated.

Hope it helps you.

Upvotes: 1

brunnerh
brunnerh

Reputation: 185489

You would need something like a dynamic import, so the import can be moved to the function and only executed when necessary. Currently, this is not really well supported, if at all.

Upvotes: 0

Related Questions