我终于搞定了,看看我的 repo Angular2 Webpack2 DotNET Starter
有几个技巧是必要的。请注意,AOT 编译不支持 Angular 2 组件中的任何 require() 语句。它们需要转换为import 语句。
首先,您需要有第二个 tsconfig.json 文件,其中包含用于 AOT 编译的特殊选项。我用.aot.json 扩展名指定它。
tsconfig.aot.json:
{
"compilerOptions": {
"target": "es5",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": false,
"noEmitHelpers": true,
"pretty": true,
"strictNullChecks": false,
"baseUrl": ".",
"sourceMap": true,
"sourceRoot": ".",
"lib": [
"es6",
"dom"
],
"types": [
"lodash",
"hammerjs",
"jasmine",
"node",
"selenium-webdriver",
"source-map",
"uglify-js",
"webpack",
"materialize-css",
"jquery",
"kendo-ui"
],
"typeRoots": [
"./node_modules/@types"
],
"outDir": "./compiled/src"
},
"exclude": [
"./node_modules",
"./**/*.e2e.ts",
"./**/*.spec.ts",
],
"awesomeTypescriptLoaderOptions": {
"useWebpackText": true,
"forkChecker": true,
"useCache": true
},
"compileOnSave": false,
"buildOnSave": false,
"atom": {
"rewriteTsconfig": false
},
"angularCompilerOptions": {
"genDir": "./compiled/aot",
"debug": true
}
}
您还需要正确的 Angular2 版本组合。 @angular/core@2.0.2 和 @angular/common@2.0.2 对我不起作用,我不得不同时使用 2.0.0 或 ngc 无法编译 AOT 文件。这是我成功使用的:
package.json:
"dependencies": {
"@angular/core": "2.0.0",
"@angular/common": "2.0.0",
"@angular/compiler": "2.0.0",
"@angular/compiler-cli": "0.6.2",
"@angular/forms": "^2.0.1",
"@angular/http": "2.0.0",
"@angular/platform-browser": "2.0.0",
"@angular/platform-browser-dynamic": "2.0.0",
"@angular/platform-server": "2.0.0",
"@angular/router": "3.0.0",
"@angular/tsc-wrapped": "0.3.0"
}
此外,您还需要几个漂亮的 webpack 加载器,同时还允许 webpack 查看 ./src 文件夹以及您的 AOT 编译文件输出到的文件夹。 (*.component.ngfactory.ts)
最后一部分非常重要!如果你不告诉 webpack 包含这些文件夹,它就不会工作。本例中,AOT 文件输出到根目录下的/aot-compiled。
webpack.common.js
loaders: [
{
test: /\.ts$/,
include: [helpers.paths.appRoot, helpers.root('./compiled/aot')],
exclude: [/\.(spec|e2e)\.ts$/],
loaders: [
'@angularclass/hmr-loader',
'awesome-typescript-loader',
'angular2-template-loader',
'angular2-router-loader?loader=system',
"angular2-load-children-loader" // this loader replaces loadChildren value to work with AOT/JIT
],
},
]
要生成您的 AOT 文件,您需要一个 NPM 脚本来为您执行此操作
package.json
"scripts": {
"compile:aot": "./node_modules/.bin/ngc -p ./tsconfig.aot.json",
}
您还需要让您的 webpack 配置读取 app.bootstrap.ts 的 AOT 版本 - 这与 JIT 版本不同。我用.aot.ts 扩展来区分它,因此在生产中,webpack 使用 AOT (app.bootstrap.aot.ts),但在开发模式下,它使用带有 webpack-dev-server (app.bootstrap.ts) 的 JIT。
最后,你运行npm run compile:aot FIRST。
将 AOT 文件输出到磁盘后,您可以使用 webpack 或 webpack-dev-server 运行 webpack 构建。
有关工作示例,请参阅我的 repo Angular2 Webpack2 DotNET Starter。它与 .NET Core 1.0 集成,但对于不使用 .NET 的用户,您仍然可以看到 Webpack 2 和 Angular 2 是如何配置的。