WebpackDevMiddleware Error with VS2017 and HotModuleReplacement = true #815

Closed
opened 2025-08-09 17:17:46 +00:00 by fergalmoran · 0 comments
Owner

Originally created by @spachara on 4/21/2017

I upgraded from VS2015 to VS2107. I got an error when I refresh a page
but If I set HMR = false is work fine. Thank you.

 app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true,
                    ConfigFile = "./webpack.dev.js",
                });

ERROR:

info: Microsoft.AspNetCore.Server.Kestrel[14]
Connection id "0HL48DGQDH7G4" communication error.
Microsoft.AspNetCore.Server.Kestrel.Internal.Networking.UvException: Error -4081 ECANCELED operation canceled
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[0]
An unhandled exception has occurred while executing the request
System.Threading.Tasks.TaskCanceledException: A task was canceled.
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Net.Http.HttpClient.d__58.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.SpaServices.Webpack.ConditionalProxyMiddleware.d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.SpaServices.Webpack.ConditionalProxyMiddleware.d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.d__6.MoveNext()

Tthis is my config
webpack.dev.js


var path = require('path');
var webpack = require('webpack');
var helpers = require('./helpers');
var webpackMerge = require('webpack-merge'); // used to merge webpack configs
var commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev
var CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
var CopyWebpackPlugin = require('copy-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;
var HtmlElementsPlugin = require('./html-elements-plugin');
var AssetsPlugin = require('assets-webpack-plugin');
var ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var nodeExternals = require('webpack-node-externals');
var AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
var settings = require('./config/dev.config');
var allFilenamesExceptJavaScript = /\.(?!js(\?|$))([^.]+(\?|$))/;
var DefinePlugin = require('webpack/lib/DefinePlugin');
var NamedModulesPlugin = require('webpack/lib/NamedModulesPlugin');

var ENV = process.env.ENV = process.env.NODE_ENV = 'development';
var HOST = process.env.HOST || 'localhost';
var PORT = process.env.PORT || 3000;
var HMR = helpers.hasProcessFlag('hot');
var METADATA = webpackMerge(commonConfig({ env: ENV }).metadata, {
  host: HOST,
  port: PORT,
  ENV: ENV,
  HMR: HMR
});
    const isDevBuild = !(ENV && ENV.prod);
    const clientBundleOutputDir = path.join(__dirname + '/wwwroot/');

    var sharedConfig = webpackMerge(commonConfig({ env: ENV }), {
        output: {
            path: clientBundleOutputDir,
            filename: 'dist/[name].bundle.js',
            publicPath: "/",
        }
    });

    var clientBundleConfig = webpackMerge(sharedConfig, {
        entry: {
            'main-client': './clientsrc/boot.ts'
        },
        devtool: isDevBuild ? 'inline-source-map' : null,
        plugins: [
         new DefinePlugin({
             'ENV': JSON.stringify(METADATA.ENV),
             'HMR': METADATA.HMR,
             'process.env': {
                 authority: JSON.stringify(settings.authority),
                 client_id: JSON.stringify(settings.client_id),
                 redirect_uri: JSON.stringify(settings.redirect_uri),
                 post_logout_redirect_uri: JSON.stringify(settings.post_logout_redirect_uri),
                 response_type: JSON.stringify(settings.response_type),
                 scope: JSON.stringify(settings.scope),

                 silent_redirect_uri: JSON.stringify(settings.silent_redirect_uri),

                 filterProtocolClaims: JSON.stringify(settings.filterProtocolClaims),
                 loadUserInfo: JSON.stringify(settings.loadUserInfo),
                 service_endpoint: JSON.stringify(settings.service_endpoint)
             }
         }),
          //new NamedModulesPlugin(),
         new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }),
         //new webpack.ProvidePlugin({ angular: 'angular'}),
          new CheckerPlugin(),
          new webpack.optimize.CommonsChunkPlugin({
              name: ['vendor'].reverse()
          }),
          new ContextReplacementPlugin(
            // The (\\|\/) piece accounts for path separators in *nix and Windows
            /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
            './clientsrc' // location of your src
          ),
          new CleanWebpackPlugin(
                    [
                         './wwwroot/dist/main.bundle.js',
                         './wwwroot/dist/vendor.bundle.js',
                         './wwwroot/fonts',
                         './wwwroot/assets'
                    ]
          ),
          new CopyWebpackPlugin([{
              from: './clientsrc/assets',
              to: 'assets'
          }]),
          new webpack.DllReferencePlugin({
              context: __dirname,
              manifest: require('./wwwroot/dist/vendor-manifest.json')
          }),
        
        ].concat(isDevBuild ? [] : [
                new webpack.SourceMapDevToolPlugin({
                    filename: '[file].map',
                    moduleFilenameTemplate: './wwwroot/[resourcePath]' 
                }),
                new webpack.optimize.OccurenceOrderPlugin(),
                new webpack.optimize.UglifyJsPlugin()
        ])
    });

    var serverBundleConfig = webpackMerge(sharedConfig, {
        resolve: { mainFields: ['main'] },
        entry: {
            'main-server': './clientsrc/boot-server.ts'
        },
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './clientsrc/')
        },
        plugins: [
            new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }),
            new webpack.ProvidePlugin({ angular: 'angular' }),
            new webpack.ProvidePlugin({ Backbone: 'backbone'}),
           new webpack.DllReferencePlugin({
               context: __dirname,
               manifest: require('./wwwroot/dist/vendor-manifest.json'),
               sourceType: 'commonjs2',
               name: './vendor'
           })
        ],
        target: 'node',
        devtool: 'inline-source-map',
        externals: [nodeExternals({ whitelist: [allFilenamesExceptJavaScript] })] // Don't bundle .js files from node_modules
    });

    module.exports = [clientBundleConfig, serverBundleConfig];

webpack.common.js


const webpack = require('webpack');
const helpers = require('./helpers');
var path = require('path');

const HMR = helpers.hasProcessFlag('hot');
const METADATA = {
  title: 'ASP.NET Core with Webpack',
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer()
};
var ENV = process.env.ENV = process.env.NODE_ENV = 'development';
var isDevBuild = !(ENV && ENV.prod);

module.exports = function(options) {
  isProd = options.env === 'production';
  return {
    stats: { modules: false },
    resolve: {      
      extensions: ['.ts', '.js', '.json', '.scss', '.css'],
    },
    
    module: {
        rules: [        
        {
          test: /\.js$/,
          loader: 'string-replace-loader',
          query: {
            search: 'var sourceMappingUrl = extractSourceMappingUrl\\(cssText\\);',
            replace: 'var sourceMappingUrl = "";',
          }
        },
         { test: /\.ts$/, include: /clientsrc/, use: ['awesome-typescript-loader?silent=true'] },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                {
                     test: /\.css$/,
                     use: ['style-loader', 'css-loader']
                },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
      ],
    }
  };
}

boot-client.ts

import 'angular2-universal-polyfills/browser';
import { enableProdMode } from '@angular/core';
import { platformUniversalDynamic } from 'angular2-universal';
import { AppModule } from './app/app.module';
import 'bootstrap';
const rootElemTagName = 'app';  

if (module['hot']) {
    module['hot'].accept();
    module['hot'].dispose(() => {
         const oldRootElem = document.querySelector(rootElemTagName);
        const newRootElem = document.createElement(rootElemTagName);
        oldRootElem.parentNode.insertBefore(newRootElem, oldRootElem);
        platform.destroy();
    });
} else {
    enableProdMode();
}

const platform = platformUniversalDynamic();
const bootApplication = () => { platform.bootstrapModule(AppModule); };
if (document.readyState === 'complete') {
    bootApplication();
} else {
    document.addEventListener('DOMContentLoaded', bootApplication);
}

boot-server.ts

import 'angular2-universal-polyfills';
import 'angular2-universal-patch';
import 'zone.js';
import { createServerRenderer, RenderResult } from 'aspnet-prerendering';
import { enableProdMode } from '@angular/core';
import { platformNodeDynamic } from 'angular2-universal';
import { AppModule } from './app/app.module';

enableProdMode();
const platform = platformNodeDynamic();

export default createServerRenderer(params => {
    return new Promise<RenderResult>((resolve, reject) => {
        const requestZone = Zone.current.fork({
            name: 'angular-universal request',
            properties: {
                baseUrl: '/',
                requestUrl: params.url,
                originUrl: params.origin,
                preboot: false,
                document: '<app></app>'
            },
            onHandleError: (parentZone, currentZone, targetZone, error) => {
                reject(error);
                return true;
            }
        });

        return requestZone.run<Promise<string>>(() => platform.serializeModule(AppModule)).then(html => {
            resolve({ html: html });
        }, reject);
    });
});
*Originally created by @spachara on 4/21/2017* I upgraded from VS2015 to VS2107. I got an error when I refresh a page but If I set HMR = false is work fine. Thank you. ``` app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true, ConfigFile = "./webpack.dev.js", }); ``` **ERROR:** info: Microsoft.AspNetCore.Server.Kestrel[14] Connection id "0HL48DGQDH7G4" communication error. Microsoft.AspNetCore.Server.Kestrel.Internal.Networking.UvException: Error -4081 ECANCELED operation canceled fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[0] An unhandled exception has occurred while executing the request System.Threading.Tasks.TaskCanceledException: A task was canceled. at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Net.Http.HttpClient.<FinishSendAsync>d__58.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.SpaServices.Webpack.ConditionalProxyMiddleware.<PerformProxyRequest>d__6.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.SpaServices.Webpack.ConditionalProxyMiddleware.<Invoke>d__5.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__6.MoveNext() **Tthis is my config** **webpack.dev.js** ``` var path = require('path'); var webpack = require('webpack'); var helpers = require('./helpers'); var webpackMerge = require('webpack-merge'); // used to merge webpack configs var commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev var CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin; var CopyWebpackPlugin = require('copy-webpack-plugin'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin; var HtmlElementsPlugin = require('./html-elements-plugin'); var AssetsPlugin = require('assets-webpack-plugin'); var ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin'); var CleanWebpackPlugin = require('clean-webpack-plugin'); var nodeExternals = require('webpack-node-externals'); var AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin'); var settings = require('./config/dev.config'); var allFilenamesExceptJavaScript = /\.(?!js(\?|$))([^.]+(\?|$))/; var DefinePlugin = require('webpack/lib/DefinePlugin'); var NamedModulesPlugin = require('webpack/lib/NamedModulesPlugin'); var ENV = process.env.ENV = process.env.NODE_ENV = 'development'; var HOST = process.env.HOST || 'localhost'; var PORT = process.env.PORT || 3000; var HMR = helpers.hasProcessFlag('hot'); var METADATA = webpackMerge(commonConfig({ env: ENV }).metadata, { host: HOST, port: PORT, ENV: ENV, HMR: HMR }); const isDevBuild = !(ENV && ENV.prod); const clientBundleOutputDir = path.join(__dirname + '/wwwroot/'); var sharedConfig = webpackMerge(commonConfig({ env: ENV }), { output: { path: clientBundleOutputDir, filename: 'dist/[name].bundle.js', publicPath: "/", } }); var clientBundleConfig = webpackMerge(sharedConfig, { entry: { 'main-client': './clientsrc/boot.ts' }, devtool: isDevBuild ? 'inline-source-map' : null, plugins: [ new DefinePlugin({ 'ENV': JSON.stringify(METADATA.ENV), 'HMR': METADATA.HMR, 'process.env': { authority: JSON.stringify(settings.authority), client_id: JSON.stringify(settings.client_id), redirect_uri: JSON.stringify(settings.redirect_uri), post_logout_redirect_uri: JSON.stringify(settings.post_logout_redirect_uri), response_type: JSON.stringify(settings.response_type), scope: JSON.stringify(settings.scope), silent_redirect_uri: JSON.stringify(settings.silent_redirect_uri), filterProtocolClaims: JSON.stringify(settings.filterProtocolClaims), loadUserInfo: JSON.stringify(settings.loadUserInfo), service_endpoint: JSON.stringify(settings.service_endpoint) } }), //new NamedModulesPlugin(), new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), //new webpack.ProvidePlugin({ angular: 'angular'}), new CheckerPlugin(), new webpack.optimize.CommonsChunkPlugin({ name: ['vendor'].reverse() }), new ContextReplacementPlugin( // The (\\|\/) piece accounts for path separators in *nix and Windows /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/, './clientsrc' // location of your src ), new CleanWebpackPlugin( [ './wwwroot/dist/main.bundle.js', './wwwroot/dist/vendor.bundle.js', './wwwroot/fonts', './wwwroot/assets' ] ), new CopyWebpackPlugin([{ from: './clientsrc/assets', to: 'assets' }]), new webpack.DllReferencePlugin({ context: __dirname, manifest: require('./wwwroot/dist/vendor-manifest.json') }), ].concat(isDevBuild ? [] : [ new webpack.SourceMapDevToolPlugin({ filename: '[file].map', moduleFilenameTemplate: './wwwroot/[resourcePath]' }), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin() ]) }); var serverBundleConfig = webpackMerge(sharedConfig, { resolve: { mainFields: ['main'] }, entry: { 'main-server': './clientsrc/boot-server.ts' }, output: { libraryTarget: 'commonjs', path: path.join(__dirname, './clientsrc/') }, plugins: [ new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), new webpack.ProvidePlugin({ angular: 'angular' }), new webpack.ProvidePlugin({ Backbone: 'backbone'}), new webpack.DllReferencePlugin({ context: __dirname, manifest: require('./wwwroot/dist/vendor-manifest.json'), sourceType: 'commonjs2', name: './vendor' }) ], target: 'node', devtool: 'inline-source-map', externals: [nodeExternals({ whitelist: [allFilenamesExceptJavaScript] })] // Don't bundle .js files from node_modules }); module.exports = [clientBundleConfig, serverBundleConfig]; ``` **webpack.common.js** ``` const webpack = require('webpack'); const helpers = require('./helpers'); var path = require('path'); const HMR = helpers.hasProcessFlag('hot'); const METADATA = { title: 'ASP.NET Core with Webpack', baseUrl: '/', isDevServer: helpers.isWebpackDevServer() }; var ENV = process.env.ENV = process.env.NODE_ENV = 'development'; var isDevBuild = !(ENV && ENV.prod); module.exports = function(options) { isProd = options.env === 'production'; return { stats: { modules: false }, resolve: { extensions: ['.ts', '.js', '.json', '.scss', '.css'], }, module: { rules: [ { test: /\.js$/, loader: 'string-replace-loader', query: { search: 'var sourceMappingUrl = extractSourceMappingUrl\\(cssText\\);', replace: 'var sourceMappingUrl = "";', } }, { test: /\.ts$/, include: /clientsrc/, use: ['awesome-typescript-loader?silent=true'] }, { test: /\.html$/, use: 'html-loader?minimize=false' }, { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' } ], } }; } ``` **boot-client.ts** ``` import 'angular2-universal-polyfills/browser'; import { enableProdMode } from '@angular/core'; import { platformUniversalDynamic } from 'angular2-universal'; import { AppModule } from './app/app.module'; import 'bootstrap'; const rootElemTagName = 'app'; if (module['hot']) { module['hot'].accept(); module['hot'].dispose(() => { const oldRootElem = document.querySelector(rootElemTagName); const newRootElem = document.createElement(rootElemTagName); oldRootElem.parentNode.insertBefore(newRootElem, oldRootElem); platform.destroy(); }); } else { enableProdMode(); } const platform = platformUniversalDynamic(); const bootApplication = () => { platform.bootstrapModule(AppModule); }; if (document.readyState === 'complete') { bootApplication(); } else { document.addEventListener('DOMContentLoaded', bootApplication); } ``` boot-server.ts ``` import 'angular2-universal-polyfills'; import 'angular2-universal-patch'; import 'zone.js'; import { createServerRenderer, RenderResult } from 'aspnet-prerendering'; import { enableProdMode } from '@angular/core'; import { platformNodeDynamic } from 'angular2-universal'; import { AppModule } from './app/app.module'; enableProdMode(); const platform = platformNodeDynamic(); export default createServerRenderer(params => { return new Promise<RenderResult>((resolve, reject) => { const requestZone = Zone.current.fork({ name: 'angular-universal request', properties: { baseUrl: '/', requestUrl: params.url, originUrl: params.origin, preboot: false, document: '<app></app>' }, onHandleError: (parentZone, currentZone, targetZone, error) => { reject(error); return true; } }); return requestZone.run<Promise<string>>(() => platform.serializeModule(AppModule)).then(html => { resolve({ html: html }); }, reject); }); }); ```
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github/JavaScriptServices#815
No description provided.