javascript - 使用服务器端渲染设置 webpack 以在 asp.net 核心项目中加载 Sass 文件

标签 javascript sass asp.net-core webpack server-side-rendering

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

我用 Angular2 创建了一个项目。biolerplate 的代码工作正常,没有问题。一旦我将 Sass 加载器添加到 webpack.config.js 并从任何 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 文件已加载并且它们的样式已正确处理。但是,一旦我运行该应用程序,就会显示来自服务器端渲染端的异常:

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

异常:调用 Node 模块失败,出现错误:ReferenceError: window is not defined at E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:573:31 at E :\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:568:48 at module.exports (E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:590:69) 在对象。 (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 在对象.module.exports (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) 在对象处。 (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在节点上无效的对象。

有什么线索吗?

最佳答案

我设法解决了这个问题,这里是 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')]
})

关于javascript - 使用服务器端渲染设置 webpack 以在 asp.net 核心项目中加载 Sass 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40414527/

相关文章:

c# - 标记助手 `Attributes` 别名

javascript - 验证输入字段为数字和特定图片尺寸

Sass 使用 @content 进行操作

sass - grunt-contrib-sass 阻止 sourcemap

c# - 未调用 ASP.NET Core AuthorizationHandler

azure - 从 ASP.NET Core 访问 Azure 应用服务 ConnectionString

c# - 在Javascript中将数组字符串解析为数组对象

javascript - Uncaught ReferenceError : 'function1' is not defined

javascript - 带有可点击侧边栏的 Google map

css - 在 SCSS 文件中导入常规 CSS 文件?