【问题标题】:angular 2 Ahead-Of-Time compilation with @ngtools/webpack, how to?angular 2 Ahead-Of-Time 编译与@ngtools/webpack,如何?
【发布时间】:2017-02-14 14:50:17
【问题描述】:

我想在 webpack 中编译 Angular 模板,但它不能完全工作。

这是我的 webpack.config.js

/// <binding ProjectOpened='Watch - Development' />
var AotPlugin = require("@ngtools/webpack").AotPlugin;

var path = require("path");
var webpack = require("webpack");
var basePath = path.join(__dirname, "wwwroot");

module.exports = {
    context: basePath,
    entry: {
        main: ["./app/main.ts"],
        productModule: "./app/components/product-module",
        adminModule: "./app/components/admin-module" 
    },
    output: {
        path: path.join(__dirname, "wwwroot/built"),
        filename: "[name].bundle.js",
        sourceMapFilename: "[name].bundle.js",
        publicPath: "built/"
    },
    module: {
        rules: [
            {
                test: /\.html$/,
                loader: "html-loader",
                query: {
                    minimize: true,
                    ignoreCustomFragments: [/\{\{.*?}}/],
                    removeAttributeQuotes: false,
                    caseSensitive: true,
                    customAttrSurround: [ [/#/, /(?:)/], [/\*/, /(?:)/], [/\[?\(?/, /(?:)/] ],
                    customAttrAssign: [ /\)?\]?=/ ] ,
                    root: basePath,
                    attrs: false // ['img:src', 'link:href']
                }
            },
            {
                test: /\.ts$/,
                loader: "@ngtools/webpack"
            }//,
           // { test: /\.css$/, loader: "style-loader!css-loader?root=." }
        ]
    },
    externals: {
        "jquery": "jQuery"
    },
    devtool: false,
    plugins: [
        new AotPlugin({
            tsConfigPath: "./tsconfig.json",
            basePath: basePath
        }),
        new webpack.optimize.CommonsChunkPlugin({
            //filename: "[name].c.bundle.js"//, 
            names: ["main"]
        })
        , new webpack.optimize.UglifyJsPlugin({
            sourceMap: true,
            minimize: true,
            acorn: true,
            angular: true,
            beautify: false,
            compress: {
                properties: true,
                sequences: true,
                dead_code: true,
                drop_debugger: true,
                unsafe_comps: true,
                conditionals: true,
                comparisons: true,
                evaluate: true,
                booleans: true,
                keep_fargs: false,
                loops: true,
                unsafe: true,
                angular: true,
                unused: true,
                cascade: true,
                hoist_funs: true,
                join_vars: true,
                warnings: false
            },
            output: {
                comments: false
            }
        })
    ]

};

还有我的 tsconfig.json:

{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es5",
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": true,
    "diagnostics": false,
    "suppressImplicitAnyIndexErrors": true
  },
  "filesGlob": [
    "**/*.ts"
  ],
  "include": [ "typings" ],
  "exclude": [ "node_modules" ],
  "angularCompilerOptions": {
    "entryModule": "app/module#AppModule"
  }
}

当我的 main.ts 导入 @angular/platform-b​​rowser 并调用 platform.bootstrapModule(AppModule);

import 'core-js';
import 'zone.js';

import { enableProdMode } from "@angular/core";
import { platformBrowser } from "@angular/platform-browser";
enableProdMode();
import { AppModule } from './module';
const platform = platformBrowser();
platform.bootstrapModule(AppModule);

然后主包的大小约为 680kB,但网站抛出:

NoProviderError_nativeError: Error: No provider for CompilerFactory!
    at NoProviderError.BaseError [as constructor] (eval at <anonymous> (http://localhost:59432/built/main.bundle.js:23:4831), <anonymous>:30:27) [<root>]
    at NoProviderError.AbstractProviderError [as constructor] (eval at <anonymous> (http://localhost:59432/built/main.bundle.js:53:73), <anonymous>:64:16) [<root>]
    at new NoProviderError (eval at <anonymous> (http://localhost:59432/built/main.bundle.js:53:73), <anonymous>:126:16) [<root>]
    at ReflectiveInjector_._throwOrNull (eval at <anonymous> (http://localhost:59432/built/main.bundle.js:84:73), <anonymous>:492:19) [<root>]
    at ReflectiveInjector_._getByKeyDefault (eval at <anonymous> (http://localhost:59432/built/main.bundle.js:84:73), <anonymous>:531:25) [<root>]
    at ReflectiveInjector_._getByKey (eval at <anonymous> (http://localhost:59432/built/main.bundle.js:84:73), <anonymous>:463:25) [<root>]
    at ReflectiveInjector_.get (eval at <anonymous> (http://localhost:59432/built/main.bundle.js:84:73), <anonymous>:332:21) [<root>]
    at PlatformRef_._bootstrapModuleWithZone (eval at <anonymous> (http://localhost:59432/built/main.bundle.js:32:7749), <anonymous>:403:62) [<root>]
    at PlatformRef_.bootstrapModule (eval at <anonymous> (http://localhost:59432/built/main.bundle.js:32:7749), <anonymous>:391:21) [<root>]
    at eval (eval at <anonymous> (http://localhost:59432/built/main.bundle.js:74:73), <anonymous>:17:10) [<root>]
    at Object.<anonymous> (http://localhost:59432/built/main.bundle.js:74:73) [<root>]
    at n (http://localhost:59432/built/main.bundle.js:1:101) [<root>]
    at Object.<anonymous> (http://localhost:59432/built/main.bundle.js:119:29) [<root>]
    at n (http://localhost:59432/built/main.bundle.js:1:101) [<root>]constructResolvingMessage: (keys)injectors: Array[1]keys: Array[1]message: (...)name: (...)stack: (...)__proto__: AbstractProviderError
ReflectiveInjector_._throwOrNull @ VM1617:492
ReflectiveInjector_._getByKeyDefault @ VM1617:531
ReflectiveInjector_._getByKey @ VM1617:463
ReflectiveInjector_.get @ VM1617:332
PlatformRef_._bootstrapModuleWithZone @ VM1627:403
PlatformRef_.bootstrapModule @ VM1627:391
(anonymous) @ VM1271:17
(anonymous) @ main.bundle.js:74
n @ main.bundle.js:1
(anonymous) @ main.bundle.js:119
n @ main.bundle.js:1
(anonymous) @ main.bundle.js:1
(anonymous) @ main.bundle.js:1

但如果我调用 platform-b​​rowser-dynamic 希望 AotPlugin 将替代导入和调用:

import 'core-js';
import 'zone.js';
import { enableProdMode } from "@angular/core";
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";
enableProdMode();
import { AppModule } from './module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);

那么 main.bundle.js 是 1076kB 这清楚地表明 platform-b​​rowser-dynamic 没有被 platform-b​​rowser 替换,并且模板编译器没有从代码树中删除。

使用 webpack 时从 bundle 中删除模板编译器的正确方法是什么(但不是在运行 webpack 之前使用 angular typescript 编译器)

我还会列出我的 package.json 以防万一:

{
  "version": "1.0.0",
  "name": "asp.net",
  "private": true,
  "scripts": {
    "start": "",
    "lite": "lite-server",
    "postinstall": "typings install && gulp restore && gulp build:sass"
  },
  "dependencies": {
    "@angular/common": "2.4.7",
    "@angular/core": "2.4.7",
    "@angular/forms": "2.4.7",
    "@angular/http": "2.4.7",
    "@angular/platform-browser": "2.4.7",
    "@angular/platform-browser-dynamic": "2.4.7",
    "@angular/router": "3.4.7",
    "@types/es6-shim": "^0.31.32",
    "animate.css": "^3.5.2",
    "aspnet-prerendering": "1.0.7",
    "bootstrap-sass": "^3.3.7",
    "concurrently": "^2.0.0",
    "css-loader": "^0.25.0",
    "es6-promise": "4.0.5",
    "es6-shim": "0.35.2",
    "core-js": "2.4.1",
    "font-awesome": "4.6.3",
    "gulp": "^3.9.1",
    "gulp-clean-css": "2.0.13",
    "gulp-rename": "1.2.2",
    "gulp-sass": "2.3.2",
    "gulp-typescript": "3.1.3",
    "gulp-webpack": "1.5.0",
    "jquery": "^2.2.4",
    "reflect-metadata": "^0.1.3",
    "rollup": "^0.36.3",
    "rxjs": "5.1",
    "style-loader": "^0.13.1",
    "systemjs": "0.19.27",
    "typings": "^1.0.4",
    "webpack": "2.2.1",
    "zone.js": "0.7.2",
    "angular-2-local-storage": "1.0.0"
  },
  "devDependencies": {
    "@ngtools/webpack": "1.2.9",
    "@angular/compiler": "^2.4.7",
    "@angular/compiler-cli": "2.4.7",
    "@types/lodash": "^4.14.52",
    "gulp": "^3.9.1",
    "gulp-clean-css": "2.0.13",
    "gulp-rename": "1.2.2",
    "gulp-sass": "2.3.2",
    "gulp-typescript": "3.1.3",
    "html-loader": "0.4.4",
    "raw-loader": "0.5.1",
    "rollup-loader": "0.1.2",
    "rollup-plugin-babel": "2.7.1",
    "typescript": "2.1.5"
  },
  "optionalDependencies": {
    "fsevents": "1.0.15"
  }
}

【问题讨论】:

    标签: angular typescript webpack angular2-aot


    【解决方案1】:

    好吧...这是新的一天,我决定调查一下这个问题。

    我去了 ./node-modules/@ngtools/webpack/src 并且我已经确定了负责替换引导代码的文件。它在文件 loader.js 中。

    我在该代码中添加了一些控制台日志:

    console.log("searching for bootstrapModule.")
        const bootstraps = allCalls
            .filter(call => call.expression.kind == ts.SyntaxKind.PropertyAccessExpression)
            .map(call => call.expression)
            .filter(access => {
            return access.name.kind == ts.SyntaxKind.Identifier
                && access.name.text == 'bootstrapModule';
            });
        console.log("bootstraps:", bootstraps.length);
    
        const calls = bootstraps
            .reduce((previous, access) => {
                console.log("previous:", previous);
                console.log("access:", access);
                const expressions = refactor.findAstNodes(access, ts.SyntaxKind.CallExpression, true);
                return previous.concat(expressions);
        }, [])
            .filter((call) => {
                console.log("call:", call);
    
            return call.expression.kind == ts.SyntaxKind.Identifier
                && call.expression.text == 'platformBrowserDynamic';
            });
        console.log("matching calls:", calls.length);
    

    找到了“bootstrapModule”部分,但没有找到“platformBrowserDynamic”。 查看代码解析的内容,我发现了这个问题。

    基本上我拥有的是:

    const platform = platformBrowserDynamic();
    platform.bootstrapModule(AppModule);
    

    虽然插件只能识别这种形式的代码:

    platformBrowserDynamic().bootstrapModule(AppModule);
    

    【讨论】:

      猜你喜欢
      • 2017-01-13
      • 2017-05-03
      • 2017-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-15
      • 2017-07-27
      相关资源
      最近更新 更多