When does webpack cli comes into play

184 Views Asked by At

How is webpack-cli used in a project?

From what I understand, as soon as I enter npm run start on my bash terminal, webpack starts running the webpack config file where I have written rules to convert jsx to js using babel, scss/less to css (correct me if I'm wrong). But where does webpack-cli comes into play in all this?

1

There are 1 best solutions below

0
On BEST ANSWER

The webpack-dev-server package is responsible to serve the build over an http server that it creates for it. It also re-starts if you make any changes to the source code (when using the hot reload option).

On the other hand, the webpack-cli package is responsible for the build and bundle of the source files. So, webpack-dev-server has to run the webpack-cli.

So you've got to have both of the packages installed.

You can see kind of how it does that in here:

https://github.com/webpack/webpack-dev-server/blob/master/bin/webpack-dev-server.js

/** @type {CliOption} */
const cli = {
  name: 'webpack-cli',
  package: 'webpack-cli',
  binName: 'webpack-cli',
  installed: isInstalled('webpack-cli'),
  url: 'https://github.com/webpack/webpack-cli',
  preprocess() {
    process.argv.splice(2, 0, 'serve');
  },
};

// ...

const runCli = (cli) => {
  if (cli.preprocess) {
    cli.preprocess();
  }
  const path = require('path');
  const pkgPath = require.resolve(`${cli.package}/package.json`);
  // eslint-disable-next-line import/no-dynamic-require
  const pkg = require(pkgPath);
  // eslint-disable-next-line import/no-dynamic-require
  require(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName]));
};

// ...

runCommand(packageManager, installOptions.concat(cli.package))
.then(() => {
  runCli(cli);
})
.catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

In webpack v5, that order kind of got reversed since you use webpack server, which is a webpack-cli call, to initiate the serve, that will call the webpack-dev-server package.

I'm not a webpack expert by any means, but I think this will help you to understand it better.