Skip to content

webpack dev script

Daniel Bischoff edited this page Apr 4, 2018 · 3 revisions

The webpack dev script helps us while developing our application. So we need an additional feature, the webpack dev server.

We do the same like in our build script. We create the webpack compiler but this time, instead of calling the compiler ourselves, we create an instance of the webpack dev server and pass the webpack compiler to this instance.

You have to put the devServer config, that is normally in your webpack config, into a separate file. This is different to running it from the cli. So take everything that is under the devServer property in your webpack config and put in in a separate file devServer.config.js under scripts.

config/devServer.config.js

// This is just an example dev server config
'use strict';
const paths = require('./paths');

module.exports = {
  compress: true,
  inline: true,
  historyApiFallback: true,
  hot: true,
  overlay: true,
  open: true,
};

Add the following content to the dev.js script.

scripts/dev.js

'use strict';
process.env.NODE_ENV = 'development';
process.env.BABEL_ENV = 'development';

const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const webpackConfig = require('../config/webpack.dev.config');
const devServerConfig = require('../config/devServer.config.js');

const HOST = '127.0.0.1';
const PORT = '9000';

// create the compiler
const compiler = webpack(webpackConfig);

// create the dev server by giving it the compiler and the dev server config
const devServer = new WebpackDevServer(compiler, devServerConfig);

// start the dev server
devServer.listen(PORT, HOST, err => {
  if (err) {
    return console.log(err);
  }

  console.log('starting the dev server...');
  console.log(`dev server listening on http://${HOST}:${PORT}`);
});

// close the dev server when killing the process or pressing ctrl + c
['SIGINT', 'SIGTERM'].forEach(function(sig) {
  process.on(sig, function() {
    devServer.close();
    process.exit();
  });
});

Now run build-config dev. This should start the dev server.

You can’t perform that action at this time.