角度2使用@ ngtools / webpack进行前期编译,如何进行?

时间:2017-02-14 14:50:18

标签: angular typescript webpack angular2-aot

我想在webpack中编译角度模板,但它不能完全发挥作用。

这是我的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

但是,如果我称平台浏览器动态,希望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,这清楚地表明平台浏览器动态没有被平台浏览器取代,模板编译器还没有从代码树中删除。

使用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"
  }
}

1 个答案:

答案 0 :(得分:1)

好的......这是新的一天,我有一个清醒的头脑,我决定调查这个问题。

我去了./node-modules/@ngtools/webpack/src,我已经确定了负责替换bootstraping代码的文件。它位于文件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);

&#39; bootstrapModule&#39;部分被发现,但平台浏览器动态&#39;不是。 看看代码正在解析什么,我发现了这个问题。

基本上我所拥有的是:

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

虽然插件只能识别该格式的代码:

platformBrowserDynamic().bootstrapModule(AppModule);