Reputation: 1234
So ive looked at documentation for webpack HMR, and cant seem to find a way to hot module load a server side file. For example, i have a config file, written in typescript, that I need to be able to reload on change to that config file. So i will need to update after compile. The docs are all favored towards using webpack dev server except this one HMR which doesnt explain what my webpack config should look like in order to use HMR. Any help or suggestions would be awesome.
Upvotes: 2
Views: 2406
Reputation: 7073
You can set it up in a very similar way to client side HMR:
1) Target 'node':
// webpack.config.js
module.exports = {
...
target: 'node'
...
}
2) Enable hot module replacement, either through the cli option --hot
or through config:
// webpack.config.js
module.exports = {
...
plugins: [new webpack.HotModuleReplacementPlugin()]
...
};
3) Include HMR management code in your entry point:
// webpack.config.js
module.exports = {
...
entry: [
'webpack/hot/poll?1000', // This differs from client side HMR
'app.js'
]
...
};
4) Teach your code how to hot update using module.hot.accept
:
NOTE: This is often abstracted away by a loader.
// app.js
let config = require('./config');
setInterval(() => {
console.log(config.FOO_BAR);
}, 2000);
// NOTE: This would need to be done everywhere you use './config' so you might want to create a loader to generate it.
if (module.hot) {
module.hot.accept('./config', () => {
config = require('./config');
});
}
4) Compile the bundle in watch mode.
Upvotes: 3