2

首先,该项目基于著名的 .Net Core 和 ng2 模板 for Visual Studio 2015 Link to VS 2015 Template Tutorial

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

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

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

在此处输入图像描述

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

在此处输入图像描述

包.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-universal 问题,我已经复制了 2 个解决方法 ts 文件并添加到 boot-server 和 boot-client 文件中。

在此处输入图像描述

webpack.config.vendor.js

正如这里所建议的,我已包含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];

引导服务器.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>页面加载时是在页面上的。否则,页面将不会首先加载。但是当底层文件发生变化时,它突然找不到了。

引导客户端.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);
}

索引.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。

4

2 回答 2

1

它需要在 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 Template Pack 中的模板。

npm i -g generator-aspnetcore-spa

yo aspnetcore-spa
于 2017-03-03T09:58:41.050 回答
0

您可以替换以下行:

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

有了这个:

module['hot'].dispose(() => { platform.onDestroy(() => { bootApplication() });
于 2017-04-19T19:04:43.127 回答