Run Webpack Watch From Node.js
May 23, 2019
If you have a Node.js server that serves content using express-static and you compile your content with Webpack, you don't have to run both npm run dev
and webpack --watch
. Your npm run dev
script can run webpack --watch
for you, no CLI required, using Webpack's Node API.
Here's an example of importing Webpack in a Node.js script and watching a file for changes. You can pass a webpack config to the webpack()
function as shown below.
const webpack = require('webpack');
// Defining the webpack config inline, but you can replace this
// with `require('./webpack.config.js')`
const config = {
mode: 'development',
entry: `${__dirname}/example/app.js`,
output: {
path: `${__dirname}/example`,
filename: 'app.min.js'
}
};
const compiler = webpack(config);
const watcher = compiler.watch({}, function(err) {
// Gets called every time Webpack finishes recompiling.
});
fs.writeFileSync(`${__dirname}/example/app.js`,
'module.exports = \'Hello, World\';');
Because of Node.js' event loop, you don't explicitly have to create new threads. Your Node process can be both an HTTP server and a Webpack compiler. Here's an example of a Node.js script:
const app = require('express')();
const webpack = require('webpack');
app.use(require('express-static')(`${__dirname}/example`));
const server = await app.listen(3000);
const config = {
mode: 'development',
entry: `${__dirname}/example/app.js`,
output: {
path: `${__dirname}/example`,
filename: 'app.min.js'
}
};
const compiler = webpack(config);
const watcher = compiler.watch({}, function(err) {
// Gets called every time Webpack finishes recompiling.
});
fs.writeFileSync(`${__dirname}/example/app.js`,
'module.exports = \'Hello, World\';');
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!