如何在Angular中动态加载外部脚本? [英] How to load external scripts dynamically in Angular?
问题描述
我有这个模块,它将外部库与其他逻辑组件化,而无需将< script>
标记直接添加到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 {...}
我注意到 import
by ES6规范是静态的,在TypeScript转换过程中而不是在运行时解析。
I notice the import
by ES6 spec is static and resolved during TypeScript transpiling rather than at runtime.
无论如何要使其可配置,以便从CDN或本地文件夹加载file.js?
如何告诉Angular 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()
:
If you're using system.js, you can use System.import()
at runtime:
export class MyAppComponent {
constructor(){
System.import('path/to/your/module').then(refToLoadedModule => {
refToLoadedModule.someFunction();
}
);
}
如果你正在使用webpack,你可以充分利用其强大的代码使用 require.ensure
:
If you're using webpack, you can take full advantage of its robust code splitting support with require.ensure
:
export class MyAppComponent {
constructor() {
require.ensure(['path/to/your/module'], require => {
let yourModule = require('path/to/your/module');
yourModule.someFunction();
});
}
}
这篇关于如何在Angular中动态加载外部脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!