Running Webpack from Node.js

Jun 4, 2019

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);

// `compiler.run()` doesn't support promises yet, only callbacks
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.


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Webpack Tutorials