我有一个工作的Angular2应用程序具有以下结构:
/app /components /moduleA /moduleB /... /shared app.module.ts app.routing.ts app.component.ts main.ts@H_301_12@现在,我正在使用systemjs-builder在我的gulp文件中创建一个包含所有typescript的单个文件:
gulp.task('bundle',() => { builder.buildStatic('app/*.js','web/bundle.app.js') .then(function() { console.log('Build complete'); }) })@H_301_12@然后在我的index.html中为我的应用程序:
<body> <app>Loading...</app> <!-- application bundle --> <script src="bundle.app.js"></script> </body>@H_301_12@一切都工作正常,但我的应用程序正在发展到多个模块,我想将它分成不同的模块文件,所以而不是bundle.app.js我有/ app /共享模块的common.js然后moduleA.js,moduleB.js等等,适用于/ app / components中的所有其他模块.
可以用systemjs-builder完成吗?这必须是一个非常常见的功能,但我在文档中看不到任何内容.
编辑:
我设法创建了一些这样的捆绑包gulp.task('bundle',() => { builder.buildStatic('app/*.js - app/components/**/*.js','web/common.js') .then(function() { console.log('Build complete'); }); builder.bundle('app/components/moduleA/**/*.js','web/moduleA.js'); builder.bundle('app/components/moduleB/**/*.js','web/moduleB.js'); })@H_301_12@但我不认为这完全没问题;我之前的单个包是2,267KB,现在我的3个模块是785KB(common.js)2,567KB(moduleA.js)1,530KB(moduleB.js),这没有意义.
如果我检查moduleA和moduleB包中的代码,我可以看到Angular2模块以及只应该是common.js的东西.
解决方法
您必须使用Bundle Arithmetic来丢弃依赖项:
https://github.com/systemjs/builder#bundle-arithmetic
您必须构建moduleA和moduleB而不引用公共文件.
获得它的一种方法是拥有这种结构:
/app app.module.ts app.routing.ts app.component.ts /modules /moduleA /moduleB /... /shared main.ts@H_301_12@然后:
gulp.task('bundle',() => { builder.buildStatic('app/**/*.js - /modules/** - /shared/**','web/app.js') builder.buildStatic('shared/**/*.js','web/common.js'); builder.bundle('modules/moduleA/**/*.js - shared/**','web/moduleA.js'); builder.bundle('modules/moduleB/**/*.js - shared/**','web/moduleB.js'); })@H_301_12@在你的HTML中:
<body> <app>Loading...</app> <!-- application bundle --> <script src="common.js"></script> <script src="moduleA.js"></script> <script src="moduleB.js"></script> <script src="app.js"></script> <script> Sytem.import(main ... balbla); </script> </body>@H_301_12@此外,您可以根据需要加载捆绑包,配置systemjs以使其成为:https://github.com/systemjs/systemjs/blob/master/docs/production-workflows.md#bundle-extension
如果您配置它,您可以使用:
<body> <app>Loading...</app> <script> Sytem.import(main ... balbla); </script> </body>@H_301_12@Systemjs在需要时加载每个bundle.