I have an issue with webpack build times in my react application. Everything builds fine but it takes a long time.
Even I change just the JavaScript files the CSS rebuilds?
Also the CSS compilation is taking a longer than I think it should be (correct me if I am wrong)?
I am running a Core i7 with 16gb of Ram and the build is taking about a minute which is becoming very annoying during development when it's a one line change and you have to wait near enough a minute before you can see your changes in the browser?
Is this the wrong approach?
const CleanObsoleteChunks = require('webpack-clean-obsolete-chunks');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const DashboardPlugin = require('webpack-dashboard/plugin');
const path = require('path');
const webpack = require('webpack');
const BUILD_DIR = path.resolve(__dirname, '../dist');
const APP_DIR = path.resolve(__dirname, 'src/');
const config = {
devtool: 'source-map',
entry: {
"ehcp-coordinator": [
APP_DIR + '/index.js'
]
},
output: {
path: `${BUILD_DIR}/js/`,
filename: '[name].js',
chunkFilename: '[name]-chunk.js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['es2015', 'es2017', 'react', 'stage-0'],
plugins: ['transform-runtime', 'transform-decorators-legacy', 'transform-class-properties', 'syntax-dynamic-import',
["import", {"libraryName": "antd", "style": false}]]
}
}
}, {
test: /\.less$/,
use: ExtractTextPlugin.extract({
use: [{
loader: "css-loader"
}, {
loader: "less-loader"
}]
})
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': "'development'"
}),
new webpack.optimize.UglifyJsPlugin({
'sourceMap': 'source-map'
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: '[name].js',
minChunks(module, count) {
var context = module.context;
return context && context.indexOf('node_modules') >= 0;
}
}),
new ExtractTextPlugin("../css/[name].css")
],
resolve: {
modules: [
path.resolve('./'),
path.resolve('./node_modules'),
],
extensions: ['.js', '.json']
}
};
module.exports = config;
As discussed in the comments, here are the most obvious changes you could make to speed up your build:
UglifyJsPlugin and ExtractTextPlugin are very heavy in terms of their impact on your compilation time, while not actually presenting many tangible benefits in development. Check process.env.NODE_ENV in your config script, and enable/disable them depending on whether you're doing a production build or not.
In place of ExtractTextPlugin, you can use style-loader in development to inject CSS into the head of the HTML page. This can cause a brief flash of unstyled content (FOUC) when the page loads, but is much quicker to build.
If you're not already, use webpack-dev-server rather than just running Webpack in watch mode - using the dev server compiles the files in memory instead of saving them to disk, which further decreases the compile times in development.
This does mean you'll have to manually run a build when you want to have the files written to disk, but you'll need to do that to switch to your production config anyway.
Not sure if this has any impact on performance, but the resolve section of your config doesn't meaningfully differ from the defaults, and you should be able to remove it without causing any issues.
In my case I updated devtool property to false.
Article on Medium: https://medium.com/#gagan_goku/hot-reloading-a-react-app-with-ssr-eb216b5464f1
Had to solve the same problem for my React app (HELO) with SSR. Things get complicated with SSR, but thankfully webpack gets a lot faster if you specify --mode=development, because it does it in memory.
webpack-dev-server did not work for me because I need the client.js bundle for the SSR client to work properly. Here's my setup:
webpack.config.js:
const path = require('path');
module.exports = {
entry: {
client: './src/client.js', // client side companion for SSR
// bundle: './src/bundle.js', // Pure client side app
},
output: {
path: path.resolve(__dirname, 'assets'),
filename: "[name].js"
},
module: {
rules: [
{
test: /\.js$/,
include: path.resolve(__dirname, 'src'),
loader: "babel-loader",
options: {
presets: [
'#babel/preset-env',
{'plugins': ['#babel/plugin-proposal-class-properties']},
],
}
}
]
},
watchOptions: {
aggregateTimeout: 1000,
poll: 500,
ignored: /node_modules/,
}
};
package.json:
"scripts": {
// IMP: --mode=development
"run-dev-ssr": "webpack --config webpack.config.js --watch --mode=development & babel src -d dist --watch & browser-refresh dist/server.js"
}
.browser-refresh-ignore:
node_modules/
static/
.cache/
.*
*.marko.js
*.dust.js
*.coffee.js
.git/
# Add these files to ignore, since webpack is storing the compiled output to assets/ folder
src/
dist/
Build times without mode:
Hash: 81eff31301e7cb74bffd
Version: webpack 4.29.5
Time: 4017ms
Built at: 05/10/2019 9:44:10 AM
Hash: 64e10f26caf6fe15068e
Version: webpack 4.29.5
Time: 2548ms
Time: 5680ms
Time: 11343ms
Build times with mode:
Hash: 27eb1aabe54a8b995d67
Version: webpack 4.29.5
Time: 4410ms
Time: 262ms
Time: 234ms
Time: 162ms
Related
*** Edit - Ignore if you want answer only ***
Seeing as this question is still receiving views and upvotes I feel responsible to share some knowledge after going through the webpack rabbithole and coming out the other end.
If you:
are building a greenfield/early-stage modern javascript project
are considering migrating from create-react-app
don't have much experience with bundling
do not need advanced features like module federation or server side rendering (which doesn't need webpack anymore)
Consider using the next generaton bundlers such as vite/parcel (easy setup), esbuild/rollup (more setup required)
Webpack was/is a fantastic contribution to the frontend world and I'm glad I learned all its intricacies, however, the new bundlers are much faster during development and easier to mantain. It's great when it works but for those inexperienced with it; despite fantastic docs the learning curve can make it a horrible pain to debug.
To clarify, I'm not a maintainer on any of these projects - just a dev who enjoys good tooling. In today's landscape, webpack is comparable to using a sledgehammer to crack a nut.
*** End of Edit ***
Webpack newbie here, I was told by webpack cli that I needed to provide an alias for crypto as webpack no longer includes default node libraries. Now I'm getting this error, other answers haven't helped so much. crypto-browserify is trying to access process.browser. Can anyone shed more light? I was told by cli to install stream-browserify too so i did.
React v17, Babel 7.12.9, webpack 5.6.0
webpack.common.js
const paths = require('./paths');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const dotenv = require('dotenv-webpack');
module.exports = {
entry: [paths.src + '/index.js'],
output: {
path: paths.build,
filename: '[name].bundle.js',
publicPath: '/',
},
plugins: [
new dotenv(),
new CleanWebpackPlugin(),
new CopyWebpackPlugin({
patterns: [
{
from: paths.public,
to: 'assets',
globOptions: {
ignore: ['*.DS_Store'],
},
},
],
}),
new HtmlWebpackPlugin({
title: 'Webpack Boilerplate',
// favicon: paths.src + '/images/favicon.png',
template: paths.src + '/template.html',
filename: 'index.html',
}),
],
resolve: {
fallback: {
crypto: require.resolve('crypto-browserify'),
stream: require.resolve('stream-browserify'),
},
},
module: {
rules: [
// javascript
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
// images
{
test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
type: 'asset/resource',
},
// Fonts and SVGs
{
test: /\.(woff(2)?|eot|ttf|otf|svg|)$/,
type: 'asset/inline',
},
// CSS, PostCSS, and Sass
{
test: /\.(scss|css)$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
esModule: true,
sourceMap: true,
importLoaders: 1,
modules: {
auto: true,
namedExport: true,
},
},
},
{ loader: 'postcss-loader', options: { sourceMap: true } },
{ loader: 'sass-loader', options: { sourceMap: true } },
],
},
],
},
};
webpack.dev.js
const webpack = require('webpack');
const { merge } = require('webpack-merge');
const common = require('./webpack.common');
module.exports = merge(common, {
mode: 'development',
// Control how source maps are generated
devtool: 'inline-source-map',
// Spin up a server for quick development
devServer: {
historyApiFallback: true,
contentBase: paths.build,
open: true,
compress: true,
hot: true,
port: 8080,
},
plugins: [
// Only update what has changed on hot reload
new webpack.HotModuleReplacementPlugin(),
],
});
In webpack 5 automatic node.js polyfills are removed. In the migration docs it is mention that
Try to use frontend-compatible modules whenever possible.
It's possible to manually add a polyfill for a node.js core module.
An error message will give a hint on how to achieve that.
Package authors: Use the browser field in package.json to make a
package frontend-compatible. Provide alternative
implementations/dependencies for the browser.
See this issue.
Now you can refer this PR and check the libs that were removed and install them.
Next add alias for the lib in your webpack config.
For ex.
resolve: {
alias: {
process: "process/browser"
}
}
Update:
This can also be done using ProvidePlugin
package.json
"devDependencies": {
...
"process": "0.11.10",
}
webpack.config.js
module.exports = {
...
plugins: [
new webpack.ProvidePlugin({
process: 'process/browser',
}),
],
}
npm i process was all I needed.
Hope the correction I proposed will be accepted and released soon
I have this problem for HtmlWebpackPlugin, I added 'templateParameters' parameter to HtmlWebpackPlugin and it was fixed for me:
new HtmlWebpackPlugin({
baseUrl: '/',
template: 'app/index.html',
templateParameters(compilation, assets, options) {
return {
compilation,
webpack: compilation.getStats().toJson(),
webpackConfig: compilation.options,
htmlWebpackPlugin: {
files: assets,
options,
},
process,
}
},
chunksSortMode: 'auto',
minify: {
collapseWhitespace: false,
},
cache: true,
}),
1. npm i dotenv-webpack
2. //Define dotenv in your webpack config
const Dotenv = require('dotenv-webpack');
plugins: [
new Dotenv({
path: './.env', // Path to .env file (this is the default)
safe: true, // load .env.example (defaults to "false" which does not use dotenv-safe)
})
],
I'm trying to launch my angular app on visual studio but when it starts, it stucks on "Loading..." section.
If i read Chrome's error console i get the following error:
Uncaught ReferenceError: require is not defined at Object. < anonymous > __ webpack_require __
The reflect-metadata contains the following: module.exports = require("reflect-metadata"); , which "require" causes the error.
Here's some of my code...
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('#ngtools/webpack').AotPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
var nodeExternals = require('webpack-node-externals');
module.exports = (env) => {
// Configuration in common to both client-side and server-side bundles
const isDevBuild = !(env && env.prod);
const sharedConfig = {
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
stats: { modules: false },
context: __dirname,
resolve: { extensions: [ '.js', '.ts' ] },
output: {
filename: '[name].js',
publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
rules: [
{ test: /\.ts$/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader', 'angular2-router-loader'] : '#ngtools/webpack' },
{ test: /\.html$/, use: 'html-loader?minimize=false' },
{ test: /\.css$/, use: [ 'to-string-loader', 'style-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
]
},
plugins: [new CheckerPlugin()]
};
// Configuration for client-side bundle suitable for running in browsers
const clientBundleOutputDir = './wwwroot/dist';
const clientBundleConfig = merge(sharedConfig, {
entry: { 'main-client': './ClientApp/boot.browser.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.UglifyJsPlugin(),
new AotPlugin({
tsConfigPath: './tsconfig.json',
entryModule: path.join(__dirname, 'ClientApp/app/app.browser.module#AppModule'),
exclude: ['./**/*.server.ts']
})
])
});
// Configuration for server-side (prerendering) bundle suitable for running in Node
const serverBundleConfig = merge(sharedConfig, {
resolve: { mainFields: ['main'] },
entry: { 'main-server': './ClientApp/boot.server.ts' },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./ClientApp/dist/vendor-manifest.json'),
sourceType: 'commonjs2',
name: './vendor'
})
].concat(isDevBuild ? [] : [
// Plugins that apply in production builds only
new AotPlugin({
tsConfigPath: './tsconfig.json',
entryModule: path.join(__dirname, 'ClientApp/app/app.server.module#AppModule'),
exclude: ['./**/*.browser.ts']
})
]),
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, './ClientApp/dist')
},
target: 'node',
devtool: 'inline-source-map'
});
return [clientBundleConfig, serverBundleConfig];
};
Searching on the internet, all of the troubleshooting suggests doing something on the systemjs.config file but mine is not an angular-cli app so I can't do it.
UPDATES SECTION
UPDATE #1
Looks like the problem is caused by webpack-node-externals executed in browser mode.
Got to find another way for that.
Got any troubleshooting or potential solution suggestion?
Thanks in advance!
UPDATE #2
I've made it, see my answer below
GOT IT!
The issue was caused by webpack-node-externals used on my common configuration.
See my question and my answer to my own question at the following: Webpack - Excluding node_modules with also keep a separated browser and server management for more details.
So, in a nutshell, the steps that I followed are these:
Installing requireJS ==> http://requirejs.org/docs/node.html
Removing externals: [nodeExternals()], // in order to ignore all modules in node_modules folder from my common webpack configuration and adding it under my server configuration (done before my question, but it's a really important step) [see webpack.config.js content in the question linked right above in this answer or in the snippet below]
Adding target: 'node', before my externals point above, under my server side section (done before my question, but it's a really important step) [see webpack.config.js content in the question linked right above in this answer or in the snippet below]
This makes sure that browser side keeps target:'web' (default target), and target becomes node just for the server.
launched webpack config vendor command manually from powershell webpack --config webpack.config.vendor.js
launched webpack config command manually from powershell webpack --config webpack.config.js
That worked for me! Hope It will works also for anyone else reading this question and encountering this issue!
webpack.config.js content:
const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('#ngtools/webpack').AotPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
var nodeExternals = require('webpack-node-externals');
module.exports = (env) => {
// Configuration in common to both client-side and server-side bundles
const isDevBuild = !(env && env.prod);
const sharedConfig = {
//removed from here, moved below.
//externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
stats: { modules: false },
context: __dirname,
resolve: { extensions: [ '.js', '.ts' ] },
output: {
filename: '[name].js',
publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
rules: [
{ test: /\.ts$/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader', 'angular2-router-loader'] : '#ngtools/webpack' },
{ test: /\.html$/, use: 'html-loader?minimize=false' },
{ test: /\.css$/, use: [ 'to-string-loader', 'style-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
]
},
plugins: [new CheckerPlugin()]
};
// Configuration for client-side bundle suitable for running in browsers
const clientBundleOutputDir = './wwwroot/dist';
const clientBundleConfig = merge(sharedConfig, {
entry: { 'main-client': './ClientApp/boot.browser.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.UglifyJsPlugin(),
new AotPlugin({
tsConfigPath: './tsconfig.json',
entryModule: path.join(__dirname, 'ClientApp/app/app.browser.module#AppModule'),
exclude: ['./**/*.server.ts']
})
])
});
// Configuration for server-side (prerendering) bundle suitable for running in Node
const serverBundleConfig = merge(sharedConfig, {
resolve: { mainFields: ['main'] },
entry: { 'main-server': './ClientApp/boot.server.ts' },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./ClientApp/dist/vendor-manifest.json'),
sourceType: 'commonjs2',
name: './vendor'
})
].concat(isDevBuild ? [] : [
// Plugins that apply in production builds only
new AotPlugin({
tsConfigPath: './tsconfig.json',
entryModule: path.join(__dirname, 'ClientApp/app/app.server.module#AppModule'),
exclude: ['./**/*.browser.ts']
})
]),
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, './ClientApp/dist')
},
//added target and externals HERE, in order to prevent webpack to read node_modules
//this also prevents fake-positives parsing errors
target: 'node',
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder,
devtool: 'inline-source-map'
});
return [clientBundleConfig, serverBundleConfig];
};
Actually, I wrote webpack for my website which was using the reactjs. In that I have lot of images and scss files so, that it is taking more amount of time to create bundle.js file upto that the website was in loading state. So, how I can increase the execution speed.
webpack.config.js
const path = require("path");
const webpack = require("webpack");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
let config = {
entry: ["babel-polyfill", "./app/js/index.js"],
output: {
path: path.resolve(__dirname, "public"),
filename: "./build.js",
//publicPath: "/"
},
resolve: {
alias: {
"js": path.resolve(__dirname, "app/js"),
"css": path.resolve(__dirname, "app/css")
},
extensions: [".js", ".jsx"]
},
module: {
rules: [
{test: /\.(js|jsx)$/, loader: "babel-loader"},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
loader: 'url-loader'
},
{test: /\.scss$/, loader: ExtractTextPlugin.extract(["css-loader", "sass-loader"])},
{test: /\.(jpg|gif|png)$/, loader: "file-loader", options: {name: "./images/[name].[ext]"}},
]
},
devServer: {
historyApiFallback: true
},
plugins: [
new HtmlWebpackPlugin({
template: "./app/index.html"
}),
new webpack.LoaderOptionsPlugin({
options: {
sassLoader: {
includePaths: ["app/css"]
}
}
}),
new ExtractTextPlugin({
filename: "style.css",
allChunks: true
})
]
};
if (process.env.NODE_ENV === "production") {
config.plugins.push(
new webpack.DefinePlugin({
"process.env": {
"NODE_ENV": JSON.stringify(process.env.NODE_ENV)
}
}),
new webpack.optimize.UglifyJsPlugin()
);
}
module.exports = config;
Besides tweaking your configuration, you could use webpack --watch to have webpack watch your source files and recompile whenever you change something. The first compilation will still be a full one, but after that only the necessary parts will be recompiled each time, which can cut down compilation time from 30 seconds to 1 or 2 seconds.
Even better is to set up webpack's devserver with hot reloading, which also watches and incrementally compiles, but in addition will update your app in the browser, so you won't need to reload the page and lose react state. It can be a bit finicky to set up, but it's well worth the trouble.
I am trying to set up webpack hot reloading with react-hot-loader. It mostly seems to be working. I am using webpack in an existing rails app.
But it isn't hot-reloading. It is simply triggering a reload every time my react code is changed. The error messages I get are:
[HMR] Cannot apply update. Need to do a full reload! - dev-server.js:18
[HMR] Error: Aborted because 0 is not accepted - dev-server.js:19
at hotApply (http://localhost:8080/assets/webpack/bundle.js?body=1:380:31)
at hotUpdateDownloaded (http://localhost:8080/assets/webpack/bundle.js?body=1:293:13)
at hotAddUpdateChunk (http://localhost:8080/assets/webpack/bundle.js?body=1:273:13)
at webpackHotUpdateCallback (http://localhost:8080/assets/webpack/bundle.js?body=1:5:12)
at http://localhost:8080/assets/webpack0.bd89931b2fa8e2901794.hot-update.js:1:1
Navigated to http://lvh.me:3000/react_page
Here is my webpack.hot.config.js settings:
var path = require('path');
var webpack = require('webpack');
var config = module.exports = {
// Set 'context' for Rails Asset Pipeline
context: __dirname,
entry: {
App: [
'webpack-dev-server/client?http://localhost:8080/', // WebpackDevServer host and port
'webpack/hot/only-dev-server', // "only" prevents reload on syntax errors
'./app/frontend/javascripts/app.js' // Your appʼs entry point
],
vendor: ['jquery', 'react', 'react-dom', 'react-redux', 'redux','redux-thunk']
},
devtool: 'inline-source-map',
// Require the webpack and react-hot-loader plugins
plugins: [
//new webpack.HotModuleReplacementPlugin(),
new webpack.optimize.CommonsChunkPlugin(
{
name: 'vendor',
chunks: [''],
filename: 'vendor.js',
minChunks: Infinity
}),
new webpack.NoErrorsPlugin(),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jquery': 'jquery'
})
],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: [
'react-hot',
'babel?presets[]=es2015&presets[]=react'
],
cacheDirectory: true
}
]
},
output: {
path: path.join(__dirname, 'app', 'assets', 'javascripts', 'webpack'), // Save to Rails Asset Pipeline
filename: 'bundle.js', // Will output App_wp_bundle.js
publicPath: 'http://localhost:8080/assets/webpack',
//publicPath: 'http://localhost:8080/assets/webpack' // Required for webpack-dev-server
},
resolve: {
extensions: ['', '.js', '.jsx'],
modulesDirectories: ['node_modules'],
},
};
And I run the code with
webpack-dev-server -d --config webpack.hot.config.js --hot --inline
The rails development environment serves the webpack files outside the application asset pipeline via the webpack-dev-server because of the following setting in my development.rb file.
config.action_controller.asset_host = Proc.new { |source|
if source =~ /webpack\/bundle\.js$/i
"http://localhost:8080"
end
}
I have been trying to get this working for hours. Any help would be appreciated.
Thanks guys!
Ok i was getting the same error, but after trying some things out i figured this out: My root component was a stateless functional component (pure function). I refactored it to a class component and BAM! the hot reloading is working again.
Before:
const App = (props) => (
<div>
<Header links={headerLinks} logoSrc={logoSrc} />
{props.children}
</div>
);
After:
class App extends React.Component {
render() {
return (
<div>
<Header links={headerLinks} logoSrc={logoSrc} />
{this.props.children}
</div>
);
}
}
As the answers provided above are still not working on my side with webpack 5,
Here is the working config from webpack
In webpack.config.js
devServer: {
.
.
.
hot: true,
}
In the webpack entrypoint index.js add
if (module.hot) {
module.hot.accept();
}
In package.json start script
"scripts": {
.
.
"start": "webpack serve --config /webpack.config.js"
},
I recently ran into this exact issue, the fix for me was removing this from the entries array: 'webpack-dev-server/client?http://localhost:9000/',.
As I was also running --hot as a command line argument, there were two instances of webpack-dev-server getting into a bad state.
I don't know if this will specifically help your issue, but I encountered this error recently as well - i fixed it by adding a .js extension to the module I was trying to set up with hmr - here was my code
if (module.hot) {
module.hot.accept('app/Routes', () => (
getRoutes = require('app/Routes')
))
}
I updated it to getRoutes = require('app/Routes.js') and the error disappeared, using webpack ^2.0.0-beta.
it also works if i add the JS extension as the first argument of hot accept like so:
if (module.hot) {
module.hot.accept('app/Routes.js', () => (
getRoutes = require('app/Routes')
))
}
so now it matches whats on the webpack HMR page
I ran into a similar problem.
After 2 days of research and trying different things, I found out the simplest cause to my problem ever:
in webpack.config.js, I had a HRM dev server enabled. And I also had a HMR server run from command line. Thanks to hint from Tyler Kelley (see above), just by removing --hot from command line, it works OK now.
current webpack.config.js
devtool: "inline-source-map",
devServer: {
publicPath: '/dist/',
contentBase: path.join(__dirname, 'public'),
port: 9000,
hot: true
},
With this configuration, don't do this:
npx webpack-dev-server --hot --inline
Do this:
npx webpack-dev-server
For "webpack": "^5.74.0" and "webpack-dev-server": "^4.11.1".
I set devServer.static = ['./webpack-dev-server', './dist'], in webpack.config.js.
There is my config:
module.exports = {
devtool: 'inline-source-map',
devServer: {
open: true,
static: ['./webpack-dev-server', './dist']
},
entry: path.join(__dirname, 'src', 'index.ts'),
module: {
rules: [
{
test: /\.(ttf|png|svg|jpg|jpeg)$/i,
type: 'asset/resource',
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.ts$/,
loader: 'ts-loader',
options: {
configFile: path.join(__dirname, 'tsconfig.json')
}
}
]
},
mode: 'development',
output: {
filename: '[name][contenthash].js',
path: path.join(__dirname, 'dist'),
clean: true,
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, 'src', 'index.html'),
inject: 'body'
})
],
resolve: {
extensions: ['.js', '.ts']
}
}
From my initial understanding of webpack's multiple entry point such as
entry: {
a: "./a",
b: "./b",
c: ["./c", "./d"]
},
output: {
path: path.join(__dirname, "dist"),
filename: "[name].entry.js"
}
It will bundle them as a.entry.js, b.entry.js and c.entry.js. There is no d.entry.js since it's part of c.
However at work, these values are confusing me so much. Why is the value an http link and not a file?
app: [
'webpack/hot/dev-server',
'webpack-dev-server/client?http://localhost:21200',
'./lib/index.js'
],
test: [
'webpack/hot/dev-server',
'webpack-dev-server/client?http://localhost:21200',
'./test/test.js'
]
As already stated in a comment on the question, the HTTP URLs are used for webpack-dev-server and its hotloading module. However, you want to ommit those modules for the production version of your bundle, since you don't need the hotloading and it makes your bundle easily over 10.000 lines of code (additionally!).
For the personal interest of the poster, here is an example production config (minimalistic), for a project of mine (called dragJs).
// file: webpack.production.babel.js
import webpack from 'webpack';
import path from 'path';
const ROOT_PATH = path.resolve('./');
export default {
entry: [
path.resolve(ROOT_PATH, "src/drag")
],
resolve: {
extensions: ["", ".js", ".scss"]
},
output: {
path: path.resolve(ROOT_PATH, "build"),
filename: "drag.min.js"
},
devtool: 'source-map',
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
include: path.resolve(ROOT_PATH, 'src')
},
{
test: /\.scss$/,
loader: 'style!css!sass'
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
};
A few things:
I only use one entry point, but you could use multiple, just as you do in your example
The entry point only refers to my js file - no webpack-dev-server for production
The config file is written using ECMAScript2015 (thus the name *.babel.js)
It uses sourcemaps and an uglify optimization plugin
The presets for the babel-loader are specified in my .babelrc file
Run webpack with this config via webpack -p --config ./webpack.production.babel.js
If there are any further questions, I would be grateful to answer them in the comments.