在ASP.NET Core项目中设置webpack进行服务器端渲染以加载Sass文件

3

我正在使用一个名为“aspnetcore-spa”的Yeoman项目模板,这是一个与主要SPA框架(Angular2和React)一起工作的ASP.net core 1模板。

我创建了一个Angular2项目。基础代码运行良好,没有问题。但是,一旦我在webpack.config.js中添加Sass loader,并从任何Angular文件引用Sass文件,问题就出现了。

在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: [
            { test: /\.ts$/, include: /ClientApp/, loader: 'ts', query: { silent: true } },
            { test: /\.scss$/,include:/ClientApp/, loaders: ["style", "css", "sass"] },
            { test: /\.html$/,include: /ClientApp/, loader: 'raw' },
            { test: /\.css$/, loader: 'to-string!css' },
            { test: /\.(png|jpg|jpeg|gif|svg)$/, loader: 'url', query: { limit: 25000 } }
        ]
    }
};

// Configuration for client-side bundle suitable for running in browsers
var clientBundleOutputDir = './wwwroot/dist';
var clientBundleConfig = merge(sharedConfig, {
    entry: { 'main-client': './ClientApp/boot-client.ts' },
    output: { path: path.join(__dirname, clientBundleOutputDir) },
    plugins: [
        new webpack.DllReferencePlugin({
            context: __dirname,
            manifest: require('./wwwroot/dist/vendor-manifest.json')
        })
    ].concat(isDevBuild ? [
        // Plugins that apply in development builds only
        new webpack.SourceMapDevToolPlugin({
            filename: '[file].map', // Remove this line if you prefer inline source maps
            moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
        })
    ] : [
        // 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];

在我的组件中:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-wine',
  template: require('./wine.component.html'),
  styles: require('./wine.component.scss')
})
export class WineComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

我已经安装了与sass加载器相关的npm包:

npm install node-sass sass-loader --save-dev

我查看了wwwroot/dist文件夹中的main-server.js文件,这是webpack打包的结果。我发现.scss文件已经被加载并且样式正确处理了。但是一旦运行应用程序,就会显示来自服务器端渲染的以下异常:

处理请求时发生未处理的异常。

异常:调用节点模块失败,出现错误:ReferenceError: window is not defined,位于E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:573:31,在E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:568:48处,在模块导出(E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:590:69)处,在Object.(E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:526:38)处,使用了webpack_require(E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:20:30),在E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:501:22处,在模块导出 (E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:506:3)处,使用了webpack_require(E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:20:30),在Object.(E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:129:25)处,使用了webpack_require(E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:20:30)

显然这是因为webpack的服务器端渲染,在Node.js端运行代码(通过ASP.net Core的JavaScript服务),而有些代码与DOM的window对象耦合,而该对象在Node上无效。

有什么线索吗?

1个回答

1
我成功解决了问题,这是web.config.js的部分代码:
(注意.scss文件的加载器)
module: {
        loaders: [
            { test: /\.ts$/, include: /ClientApp/, loader: 'ts', query: { silent: true } },
            { test: /\.scss$/,include:/ClientApp/, loaders: ["to-string", "css", "sass"] },
            { test: /\.html$/,include: /ClientApp/, loader: 'raw' },
            { test: /\.css$/, loader: 'to-string!css' },
            { test: /\.(png|jpg|jpeg|gif|svg)$/, loader: 'url', query: { limit: 25000 } }
        ]
    }

在 Angular 组件中,我将样式更改为以下内容:(传递了一个所需 css 文件的数组,而不是单个 css 文件)
@Component({
  selector: 'app-wine',
  template: require('./wine.component.html'),
  styles: [require('./wine.component.scss')]
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接