As pointed out by @aprisniak, Ling's answer is sufficient but Nodemon throws an error if the specified watch file doesn't exist. Although there is an issue to watch for a non-existent file on Nodemon's GitHub page, the feature doesn't exist. My workaround is similar to Ling's answer but I use concurrently instead of npm-run-all.
To fix the issue, introduce a script to touch your watch file before Nodemon starts up.
package.json
"scripts": {
"_stopNodemonCrash": "mkdir -p dist && touch ./dist/server.js",
"_nodemon": "yarn _stopNodemonCrash && nodemon ./dist/server.js",
"dev": "rm -rf dist && concurrently -n webpack,nodemon \"webpack\" \"yarn _nodemon\""
}
In your webpack config, make sure that you have watch
set to true
and that you include whatever specific watch options you need.
webpack.config.js
{
mode: 'development',
entry: {
server: './src/server/server.js',
},
output: {
path: path.join(__dirname, '..', 'dist'),
publicPath: '/',
filename: '[name].js',
},
watch: true,
watchOptions: {
poll: 1000,
ignored: /node_modules/,
aggregateTimeout: 300,
},
...
}
Here's what happens when you run yarn dev
:
- The build directory is cleared
- Webpack runs and bundles all your code into the build directory WHILE Nodemon starts up and watches the bundled server.js file for changes (without crashing)
- You get to see a nice little output as shown below
[nodemon] [nodemon] 2.0.21
[nodemon] [nodemon] to restart at any time, enter `rs`
[nodemon] [nodemon] or send SIGHUP to 68591 to restart
[nodemon] [nodemon] watching path(s): dist/server.js
[nodemon] [nodemon] starting `node ./dist/server.js`
[nodemon] [nodemon] forking
[nodemon] [nodemon] child pid: 68599
[nodemon] [nodemon] watching 1 file
[nodemon] [nodemon] clean exit - waiting for changes before restart
[webpack] asset server.js 41.8 KiB [emitted] (name: server)
[webpack] asset src_server_modules_config_js.js 38.4 KiB [emitted]
[webpack] asset src_server_modules_hmr_js.js 16.8 KiB [emitted]
[webpack] asset webpack_webpack_client_dev_config_js.js 4.21 KiB [emitted]
[webpack] cached modules 63.5 KiB (javascript) 5.46 KiB (runtime) [cached] 46 modules
[webpack] webpack 5.75.0 compiled successfully in 1967 ms
[nodemon] [nodemon] files triggering change check: dist/server.js
[nodemon] [nodemon] matched rule: **/dist/server.js
[nodemon] [nodemon] changes after filters (before/after): 1/1
[nodemon] [nodemon] restarting due to changes...
[nodemon] [nodemon] dist/server.js
[nodemon]
[nodemon] [nodemon] starting `node ./dist/server.js`
[nodemon] [nodemon] forking
[nodemon] [nodemon] child pid: 68611
[nodemon]
[nodemon] --------------listening on: 8080-----------------
webpack.server.config.js
? – Nordau