akazemis akazemis - 29 days ago 25
Javascript Question

Setup webpack with server side rendering to load Sass files in asp.net core project

I'm using a Yeoman project template called "aspnetcore-spa", which is an ASP.net core 1 template working in conjunction with major SPA frameworks (Angular2 and React).

I created a project with Angular2.The biolerplate's code works fine and there is no problem. Once I add Sass loader to webpack.config.js and make a reference to the Sass file from any angular file.

In 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];


In my component :

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() {
}

}


I have already installed npm packages pertinent to sass loader :

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


I have checked the main-server.js file in wwwroot/dist folder which is the result of webpack bundling, I saw that the .scss file is loaded and they styles are processed correctly. Once I run the app though, shows this exception which is coming from the server side rendering side:

An unhandled exception occurred while processing the request.

Exception: Call to Node module failed with error: ReferenceError: window is not defined at E:\Dev\Ixup\IxupCore\src\Ixup.Web\ClientApp\dist\main-server.js:573:31 at E:\Dev\Ixup\IxupCore\src\Ixup.Web\ClientApp\dist\main-server.js:568:48 at module.exports (E:\Dev\Ixup\IxupCore\src\Ixup.Web\ClientApp\dist\main-server.js:590:69) at Object. (E:\Dev\Ixup\IxupCore\src\Ixup.Web\ClientApp\dist\main-server.js:526:38) at webpack_require (E:\Dev\Ixup\IxupCore\src\Ixup.Web\ClientApp\dist\main-server.js:20:30) at E:\Dev\Ixup\IxupCore\src\Ixup.Web\ClientApp\dist\main-server.js:501:22 at Object.module.exports (E:\Dev\Ixup\IxupCore\src\Ixup.Web\ClientApp\dist\main-server.js:506:3) at webpack_require (E:\Dev\Ixup\IxupCore\src\Ixup.Web\ClientApp\dist\main-server.js:20:30) at Object. (E:\Dev\Ixup\IxupCore\src\Ixup.Web\ClientApp\dist\main-server.js:129:25) at webpack_require (E:\Dev\Ixup\IxupCore\src\Ixup.Web\ClientApp\dist\main-server.js:20:30)

It's obviously because of the webpack's server-side rendering, as it's running the code on Node.js side (through ASP.net Core's Javascript Services) and there is a code that is coupled with the DOM
window
object which is not valid on node.

Any clues?

Answer

I managed to fix the problem, here's the web.config.js bit:

(Notice the loaders for .scss files)

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 } }
        ]
    }

And in the Angular component I changed the styles to this :

(Passed an array of required css files rather than a single css file)

@Component({
  selector: 'app-wine',
  template: require('./wine.component.html'),
  styles: [require('./wine.component.scss')]
})