如何让webpack-dev-server自动重建打包无需重复执行命令?
Hey there! I see you're running into an issue where webpack-dev-server isn't picking up new, renamed, or deleted JS files while it's running—let's fix that right up.
The Root Cause
Your current webpack config uses glob.sync('./src/**/*.js*') directly in the entry object. The problem here is that glob.sync runs only once when webpack first starts up. It scans your files at that moment and creates the entry bundle list, but it doesn't re-scan when you add/remove/rename files later. That's why your new c.js never gets added to main.js while the dev server is running.
The Fix
We need to make webpack re-scan your JS files every time it triggers a compilation. The easiest way to do this is to turn your entry into a function that returns the entry object. Here's how to update your config:
Modify the entry section in
webpack.config.js:
Replace your existing entry block with this:entry: () => ({ main: glob.sync('./src/**/*.js*') }),This function will run every time webpack starts a compilation (triggered by file changes), so it'll always grab the latest list of JS files.
Confirm your watch settings:
You already havewatch: truein your config, which is perfect—this ensures webpack keeps an eye on file changes and triggers re-compilations automatically.
Test It Out
Restart your dev server with npm run dev, then follow your reproduction steps again:
- Create
c.js(copying the plugin structure fromhide.js/show.jsand updating thepluginName) - Add the
data-clickableelement toindex.pug - Refresh your browser and click the new element—your JS should now run as expected, no need to restart the dev server!
Extra Tips
- Double-check your glob pattern: Make sure
./src/**/*.js*matches where all your JS files live. If your files are in a specific subfolder likesrc/javascript, adjust the pattern to./src/javascript/**/*.js*for more accuracy. - Update CleanWebpackPlugin (optional): Your current
CleanWebpackPluginuses deprecated syntax (watch: true). If you upgrade to the latest version (npm install clean-webpack-plugin@latest), you can simplify the plugin initialization to justnew CleanWebpackPlugin()—it'll automatically clean thedistfolder on each build.
内容的提问来源于stack exchange,提问作者John

