Angular2 webpack/hmr 更改后无法加载

Angular2 webpack/hmr could not load after the changes

首先,该项目基于 Visual Studio 2015 Link to VS 2015 Template Tutorial

著名的 .Net Core 和 ng2 模板

这个模板非常好,一切正常,符合预期。 Webpack/HMR 也在工作,每当我更改 .html 或 .ts 文件时,我都能立即看到更改。

但是,它使用的是非常旧版本的库。当我决定将所有库升级到最新版本(WebPack 到 2.2.1)时,问题就开始了。由于这次升级过程中的重大突破性变化,我遇到了很多错误。除了最后一期,我设法解决了几乎所有问题并像往常一样启动了应用程序和 运行。

它不再使用 HotModuleReplacement (HMR) 加载更改。当我在浏览器上刷新 (F5) 时,所有更改都会反映在页面上。

我们可以在这里看到它确实知道更改,编译并返回最新(正确)的 html 代码,但无法将其加载回页面。它一直说 Selector 'app' did not match any elements.

package.json

"dependencies": {
    "@angular/common": "^2.4.8",
    "@angular/compiler": "^2.4.8",
    "@angular/core": "^2.4.8",
    "@angular/forms": "^2.4.8",
    "@angular/http": "^2.4.8",
    "@angular/platform-browser": "^2.4.8",
    "@angular/platform-browser-dynamic": "^2.4.8",
    "@angular/platform-server": "^2.4.8",
    "@angular/router": "^3.4.8",
    "@types/node": "^7.0.5",

    "angular2-platform-node": "^2.1.0-rc.1",
    "angular2-universal": "^2.1.0-rc.1",
    "angular2-universal-polyfills": "^2.1.0-rc.1",
    "aspnet-prerendering": "^2.0.3",
    "aspnet-webpack": "^1.0.27",
    "bootstrap": "^3.3.7",
    "css": "^2.2.1",
    "css-loader": "^0.26.1",
    "es6-shim": "^0.35.1",
    "expose-loader": "^0.7.3",
    "extract-css-block-webpack-plugin": "^1.3.0",
    "extract-text-webpack-plugin": "^2.0.0-beta",

    "file-loader": "^0.10.0",
    "isomorphic-fetch": "^2.2.1",
    "jquery": "^3.1.1",
    "preboot": "^4.5.2",
    "raw-loader": "^0.5.1",
    "rxjs": "^5.2.0",
    "style-loader": "^0.13.1",
    "to-string-loader": "^1.1.5",
    "ts-loader": "^2.0.1",
    "typescript": "^2.2.1",
    "url-loader": "^0.5.7",
    "webpack": "^2.2.1",
    "webpack-externals-plugin": "^1.0.0",
    "webpack-hot-middleware": "^2.17.0",
    "webpack-merge": "^3.0.0",
    "zone.js": "^0.7.7"
  }

对于一个众所周知的 angular-普遍问题,我已经复制了 2 个解决方法 ts 文件并添加到引导服务器和引导客户端文件中。

webpack.config.vendor.js

按照建议 here,我已将 aspnet-prerendering 包含在供应商条目中。

var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    resolve: {
        extensions: [ '*', '.js' ]
    },
    module: {
        loaders: [
            { test: /\.(png|woff|woff2|eot|ttf|svg)(\?|$)/, loader: 'url-loader?limit=100000' },
            { test: /\.css(\?|$)/, loader: ExtractTextPlugin.extract("css-loader") }
        ]
    },
    entry: {
        vendor: [
            '@angular/common',
            '@angular/compiler',
            '@angular/core',
            '@angular/http',
            '@angular/platform-browser',
            '@angular/platform-browser-dynamic',
            '@angular/router',
            '@angular/platform-server',
            'angular2-universal',
            'angular2-universal-polyfills',
            'bootstrap',
            'bootstrap/dist/css/bootstrap.css',
            'es6-shim',
            'es6-promise',
            'jquery',
            'zone.js',
            'aspnet-prerendering' 
        ]
    },
    output: {
        path: path.join(__dirname, 'wwwroot', 'dist'),
        filename: '[name].js',
        library: '[name]_[hash]',
    },
    plugins: [
        //extractCSS,
        new ExtractTextPlugin({
            filename: "vendor.css",
            allChunks: true
        }),
        new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
        new webpack.optimize.OccurrenceOrderPlugin(),
        new webpack.DllPlugin({
            path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
            name: '[name]_[hash]'
        })
    ].concat(isDevBuild ? [] : [
        new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } })
    ])
};

webpack.config.js

var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
var nodeExternals = require('webpack-node-externals');
var merge = require('webpack-merge');
var allFilenamesExceptJavaScript = /\.(?!js(\?|$))([^.]+(\?|$))/;

// Configuration in common to both client-side and server-side bundles
var sharedConfig = {
    resolve: { extensions: [ '*', '.js', '.ts' ] },
    output: {
        filename: '[name].js',
        publicPath: '/dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
    },
    module: {
        loaders: [
            {   // TypeScript files
                test: /\.ts$/,
                include: /ClientApp/,
                exclude: [/\.(spec|e2e)\.ts$/], // Exclude test files | end2end test spec files etc
                loaders: [
                'ts-loader?silent=true'
                ]
            },
            { test: /\.html$/, loader: 'raw-loader' },
            { test: /\.css$/, loader: 'raw-loader' },
            { test: /\.(png|jpg|jpeg|gif|svg)$/, loader: 'url-loader', query: { limit: 25000 } }
        ]
    }
};

// Configuration for client-side bundle suitable for running in browsers
var clientBundleConfig = merge(sharedConfig, {
    entry: { 'main-client': './ClientApp/boot-client.ts' },
    output: { path: path.join(__dirname, './wwwroot/dist') },
    devtool: isDevBuild ? 'inline-source-map' : null,
    plugins: [
        new webpack.DllReferencePlugin({
            context: __dirname,
            manifest: require('./wwwroot/dist/vendor-manifest.json')
        })
    ].concat(isDevBuild ? [] : [
        // Plugins that apply in production builds only
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin()
    ])
});

// Configuration for server-side (prerendering) bundle suitable for running in Node
var serverBundleConfig = merge(sharedConfig, {
    entry: { 'main-server': './ClientApp/boot-server.ts' },    
    output: {
        libraryTarget: 'commonjs',
        path: path.join(__dirname, './ClientApp/dist')
    },
    target: 'node',
    devtool: 'inline-source-map',
    externals: [nodeExternals({ whitelist: [allFilenamesExceptJavaScript] })] // Don't bundle .js files from node_modules
});

module.exports = [clientBundleConfig, serverBundleConfig];

boot.server.ts

import 'angular2-universal-polyfills';
import 'zone.js';
import './__workaround.node'; // temporary until 2.1.1 things are patched in Core

import { enableProdMode } from '@angular/core';
import { platformNodeDynamic } from 'angular2-universal';
import { AppModule } from './app/app.module';

//enableProdMode();
const platform = platformNodeDynamic();

import { createServerRenderer, RenderResult  } from 'aspnet-prerendering';

export default createServerRenderer(params => {

    // Our Root application document
    const doc = '<app></app>';

    return new Promise<RenderResult>((resolve, reject) => {
        const requestZone = Zone.current.fork({
            name: 'Angular-Universal Request',
            properties: {
                ngModule: AppModule,
                baseUrl: '/',
                requestUrl: params.url,
                originUrl: params.origin,
                preboot: false,
                document: doc
            },
            onHandleError: (parentZone, currentZone, targetZone, error) => {
                // If any error occurs while rendering the module, reject the whole operation
                reject(error);
                return true;
            }
        });

        return requestZone.run<Promise<string>>(() => platform.serializeModule(AppModule)).then(html => {
            resolve({ html: html });
        }, reject);
    });
});

很明显 <app></app> 在页面加载时就在页面上。否则,页面不会首先加载。但是当底层文件发生变化时突然找不到了。

boot.client.ts

import 'angular2-universal-polyfills/browser';
import './__workaround.browser'; // temporary until 2.1.1 things are patched in Core
import { enableProdMode } from '@angular/core';
import { platformUniversalDynamic } from 'angular2-universal';
import { AppModule } from './app/app.module';
import 'bootstrap';

// Enable either Hot Module Reloading or production mode
if (module['hot']) {
    module['hot'].accept();
    module['hot'].dispose(() => { platform.destroy(); });
} else {
    enableProdMode();
}

// Boot the application, either now or when the DOM content is loaded
const platform = platformUniversalDynamic();
const bootApplication = () => { platform.bootstrapModule(AppModule); };
if (document.readyState === 'complete') {
    bootApplication();
} else {
    document.addEventListener('DOMContentLoaded', bootApplication);
}

Index.html

@{
    ViewData["Title"] = "Home Page";
}

<app asp-prerender-module="ClientApp/dist/main-server">Loading...</app>

<script src="~/dist/vendor.js" asp-append-version="true"></script>
@section scripts {
    <script src="~/dist/main-client.js" asp-append-version="true"></script>
}

你们能帮我解决这个错误吗?谢谢。

我确实尝试将这个放在 Plunkr 上,但我不知道如何将 .NetCore 文件上传到 Plunkr。

它需要在 boot.client.ts 中更改才能与最新的 webpack-hmr 库一起使用。

// Enable either Hot Module Reloading or production mode
if (module['hot']) {
    module['hot'].accept();
    module['hot'].dispose(() => {
        // Before restarting the app, we create a new root element and dispose the old one
        const oldRootElem = document.querySelector(rootElemTagName);
        const newRootElem = document.createElement(rootElemTagName);
        oldRootElem.parentNode.insertBefore(newRootElem, oldRootElem);
        platform.destroy();
    });
} else {
    enableProdMode();
}

问题是这个模板很旧,需要大量更改才能适应最新的 angular2 和 webpack 库。

我建议使用这些命令来安装 Angular2Spa 并创建 ng2 项目,而不是使用 AspNetCore 模板包中的模板。

npm i -g generator-aspnetcore-spa

yo aspnetcore-spa

您可以替换以下行:

module['hot'].dispose(() => { platform.destroy(); });

有了这个:

module['hot'].dispose(() => { platform.onDestroy(() => { bootApplication() });