Reputation: 131
I downloaded webpack v5.75.0, and I have a small project with the following folder structure:
`
my-project
-dist
--index.html
--assets
---bundle.js
-src
--index.js
package.json
webpack.config.js
`
I installed webpack-dev-server via npm, and I would like to keep it running while watching for any code changes in my -src directory, such that all files in the -dist directory automatically get updated as I save changes to my source code.
Below is the dev dependencies in my package.json file: `
"devDependencies": {
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1",
"webpack-dev-server": "^4.11.1"
}
`
Below is the content of my webpack.config.js file: `
const path = require('path');
module.exports = {
mode: 'development',
watch: true,
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist', 'assets'),
publicPath: './dist/assets',
},
devServer: {
static: './src',
},
};
`
I run webpack dev server with the following command: npx webpack-dev-server
but when I save my changes in index.js, it does not automatically update in bundle.js as I would expect.
I suspect the problem lies in my webpack.config.js file, but I am not sure what I did wrong.
I tried configuring webpack.config.js devServer object to point to ./dist directory as follows:
devServer: {
static: './dist',
},
Upvotes: 4
Views: 1774
Reputation: 1
I have the same setup in folders and files.
First I created a dev.config.js file and added it to the script section of package.json like this:
"scripts": {
"dev": "webpack-dev-server --config ./dev.config.js",
},
I think the problem is in your config.sys. It should look like this:
const path = require('path');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist/assets'),
filename: 'bundle.js',
clean: true,
},
devServer: {
static: {
directory: path.join(__dirname, 'dist'), // points to index.html location
},
devMiddleware: {
publicPath: '/assets/' // this is very, very important if you want this to run
},
hot: true,
open: true,
},
}
Your devServer points to the source folder, not the location of the index.html (which is in the dist folder).
You need to set the public path for the devServer and point it to the correct location (where your bundle.js is). Create a devMiddleware section like above and add this to your config file.
You do not need to watch files because webpack-dev-server takes care of this for you.
After this your environment should run as expected
Upvotes: 0