The problem is that I get this very error Failed to load resource: the server responded with a status of 404 (Not Found)
when I use webpack-dev-server.
But if I just build the project then I can run my index.html
and get the expected result.
My project structure is:
public/
index.html
assets/
src/
index.js
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>PBWA</title>
</head>
<body>
<div id="root"></div>
</body>
<script src="assets/bundle.js"></script>
</html>
And here're webpack config files
webpack.common.js
const path = require('path')
const CleanWebpackPlugin = require('clean-webpack-plugin')
module.exports = {
entry: './src/index.js',
plugins: [
new CleanWebpackPlugin(['assets'])
],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'public/assets')
}
}
webpack.dev.js
const merge = require('webpack-merge')
const common = require('./webpack.common.js')
module.exports = merge(common, {
devtool: 'inline-source-map',
devServer: { contentBase: './public' }
})
webpack.prod.js
const merge = require('webpack-merge')
const common = require('./webpack.common.js')
const webpack = require('webpack')
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
module.exports = merge(common, {
devtool: 'source-map',
plugins: [
new UglifyJSPlugin({ sourceMap: true }),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
})
]
})
So when I run webpack-dev-server --open --config webpack.dev.js
CLI command then I get the error.
And when I run webpack --config webpack.prod.js
and then open index.html
everything works just fine.
My question is why does webpack-dev-server behaves that oddly? What am I missing?
Ok the problem is solved. As far as webpack-dev-server doesn't actually create any files in project tree but loads them directly into memory and that's why we don't get bundle.js
file in our assets
folder. Next we use devServer
in development mode and we set it's contentBase
property which is to tell the server where to serve content from. But by default bundled files will be available in the browser under publicPath
which is /
by default. As far as we have assigned assets
directory for this purpose we need to tell webpack to change it's defaults and assign /assets/
to publicPath
property of devServer
options.
Finally, here's the code to solve the problem:
in webpack.dev.js
...
devServer: {
publicPath: "/assets/", // here's the change
contentBase: path.join(__dirname, 'public')
}
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With