问题描述
我有这个模块将外部库与附加逻辑一起组件化,而无需将 <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 {...}
我注意到 ES6 规范中的 import
是静态的,并且在 TypeScript 转译期间而不是在运行时解析.
I notice the import
by ES6 spec is static and resolved during TypeScript transpiling rather than at runtime.
无论如何要使其可配置,以便 file.js 将从 CDN 或本地文件夹加载?如何告诉 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 中动态加载外部脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!