Running Webpack from Node.js

Most developers use Webpack via the Webpack CLI, but Webpack also has an excellent Node.js API. That means you can run Webpack from your Node.js scripts, like an Express server, without a task runner.

For example, suppose you have the below webpack.config.js file. It takes a file app.js , and compiles it into ./bin/app.min.js .

module .exports = { mode : 'development' , entry : { app : ` ${__dirname} /app.js` }, target : 'web' , output : { path : ` ${__dirname} /bin` , filename : '[name].min.js' } };

Normally, you would run webpack from the command line. But you can also require('webpack') and run this config script from Node.js:

const config = require ( './webpack.config.js' ); const webpack = require ( 'webpack' ); const compiler = webpack(config); await new Promise ( ( resolve, reject ) => { compiler.run( ( err, res ) => { if (err) { return reject(err); } resolve(res); }); });

You can also run webpack --watch from Node.js.

More Webpack Tutorials