最近开发的一款移动应用用了Angular2框架,直接ng build的话动不动程序就要好几M,于是采取Angular2的aot编译及Rollup优化压缩程序。
过程遇坑无数,说多了都是泪,现在问题解决了就小结下与大家分享:
- 新建一个项目
ng new myapp
- 复制src/tsconfig.json到根目录下,重命名为tsconfig-aot.json并编辑:
{
"compilerOptions": {
"target": "es5",
"module": "es2015",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es2015", "dom"],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"typeRoots": [
"node_modules/@types/"
]
},
"files": [
"src/app/app.module.ts",
"src/main-aot.ts"
],
"angularCompilerOptions": {
"genDir": "aot",
"skipMetadataEmit" : true
}
}
- 复制src/main.ts文件重命名为main-aot.ts,把它改为AOT编译:
import { platformBrowser } from '@angular/platform-browser';
import { AppModuleNgFactory } from '../aot/src/app/app.module.ngfactory';
platformBrowser().bootstrapModuleFactory(AppModuleNgFactory);
- 接下来安装少量新的npm依赖(有时报错可分开安装):
npm install @angular/compiler-cli @angular/platform-server --save
- Rollup 工具安装
npm install rollup rollup-plugin-node-resolve rollup-plugin-commonjs rollup-plugin-uglify --save-dev
- 接下来,在项目根目录新建一个配置文件rollup-config.js,来告诉Rollup如何处理应用。
import nodeResolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import uglify from 'rollup-plugin-uglify';
export default {
entry: 'src/main.js',
dest: 'src/build.js', // output a single application bundle
sourceMap: false,
format: 'iife',
onwarn: function(warning) {
// Skip certain warnings
// should intercept ... but doesn't in some rollup versions
if ( warning.code === 'THIS_IS_UNDEFINED' ) { return; }
// console.warn everything else
console.warn( warning.message );
},
plugins: [
nodeResolve({jsnext: true, module: true}),
commonjs({
include: 'node_modules/rxjs/**',
}),
uglify()
]
};
- 更便利的脚本,在package.json中添加:
"build:aot": "ngc -p tsconfig-aot.json && rollup -c rollup-config.js",
"serve:aot": "lite-server -c bs-config.aot.json",
- 打开终端尝试下(顺利的话会在aot文件下生成dist/build.js):
npm run build:aot
- 然后重点来了,在根目录下创建copy-dist-files.js文件:
var fs = require('fs');
var resources = [
'node_modules/core-js/client/shim.min.js',
'node_modules/zone.js/dist/zone.min.js',
'src/styles.css'
];
resources.map(function(f) {
var path = f.split('/');
var t = 'aot/' + path[path.length-1];
fs.createReadStream(f).pipe(fs.createWriteStream(t));
});
终端运行:
node copy-dist-files
会得到项目所需的3文件,之前就是一直欠缺里面的两个js文件导致一直出错(当然手动引入也是可以的)!
- 最后在aot目录下补上index.html整个项目就算优化完成了,只需保留几个引入的文件即可,赶紧在服务器下试一试吧~
<!DOCTYPE html>
<html>
<head>
<base href="/">
<title>myAPP</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<script src="shim.min.js"></script>
<script src="zone.min.js"></script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
<script src="dist/build.js"></script>
</html>