[英]Properly configure scripts with Angular-CLI
Let's say I have a project which uses these JS libraries: 假设我有一个使用这些JS库的项目:
main.js
which has to be loaded in all pages main.js
必须在所有页面中加载 joe.js
which is a npm package to be loaded in all pages joe.js
是一个在所有页面中加载的npm包 bob.js
which is an old-style 3rd party JS library with no module defined to be loaded in all pages bob.js
是一个旧式的第三方JS库,没有定义要在所有页面中加载的模块 max.js
which is a CommonJS library to be loaded on-demand in some components max.js
是一些在某些组件中按需加载的CommonJS库 So far, I succeded in: 到目前为止,我成功了:
main.js
in the scripts
property of angular-cli.json
main.js
在scripts
的属性angular-cli.json
joe.js
using relative paths ( ../node_modules/joe/dist/joe.js
) joe.js
使用相对路径( ../node_modules/joe/dist/joe.js
) so they end up in the generated bundle that is loaded on every page. 所以它们最终会出现在每个页面上加载的生成包中。
I had instead a lot of problems with the other two. 与其他两个相比,我遇到了很多问题。 So far I've managed to include
bob.js
in the bundle by wrapping it in a self-executing function: 到目前为止,我已经设法通过将
bob.js
包装在一个自动执行的函数中来包含它:
(function() {
// old code of bob.js
})();
but why? 但为什么呢? And I'm totally clueless on how to include/bundle
max.js
... 而且我对如何包含/捆绑
max.js
完全无能为力......
For main, joe and bob.js
you should do this: 对于
main, joe and bob.js
你应该这样做:
To have the scripts available everywhere you can use the src/assets
folder in your angular-cli folder structure. 要使脚本在任何地方都可用,您可以使用angular-cli文件夹结构中的
src/assets
文件夹。
And then include your scripts with: 然后包含您的脚本:
<script src="assets/my-script.js"></script>
As an option you can get those dependencies from node_modules
to src/assets
with a webpack. 作为一个选项,您可以使用
node_modules
将这些依赖项从node_modules
到src/assets
。
For most cases using CDN is better option than all this. 对于大多数使用CDN的情况来说,比这一切更好。
As for max.js
you i would create a service to conveniently inject it: 至于
max.js
你我会创建一个服务来方便地注入它:
import { Injectable } from '@angular/core';
@Injectable()
export class MaxService {
lib: any;
constructor(){
this.lib = require('max.js');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.