动态加载外部JS脚本在2角

问题描述:

我有这个模块,用额外的逻辑一起组件化的外部库而不添加<脚本> 标记直接进入的index.html:

I have this module which componentize the external library together with additional logic without adding the <script> tag directly into the index.html:

import 'http://external.com/path/file.js'
//import '../js/file.js'

@Component({
    selector: 'my-app',
    template: `
        <script src="http://iknow.com/this/does/not/work/either/file.js"></script>
        <div>Template</div>`
})
export class MyAppComponent {...}

我注意到导入按ES6规范是静态的,并且在打字稿transpiling,而不是在运行时解决。

I notice the import by ES6 spec is static and resolved during TypeScript transpiling rather than at runtime.

不管怎样,使其配置使file.js将从CDN或本地文件夹加载要么?
如何分辨角2动态加载脚本?

Anyway to make it configurable so the file.js will be loading either from CDN or local folder? How to tell Angular 2 to load a script dynamically?

假设你正在使用system.js,你可以在运行时使用 System.import()

Assuming you're using system.js, you can use System.import() at runtime:

export class MyAppComponent {

  constructor(){
    System.import('path/to/your/file').then(refToLoadedScript => {
      refToLoadedScript.someFunction();
    }
  );
}