How to fix Error: Cannot find module 'webpack' in JavaScript

When using webpack in your JavaScript application, you might encounter errors related to the module as follows:

  1. Cannot find module ‘webpack’
  2. Cannot find module ‘webpack-cli’
  3. Cannot find module ‘webpack/bin/config-yargs’

These errors commonly occur when your webpack module isn’t downloaded and installed properly.

Let’s see what you can do to fix the errors in this guide.

1. Cannot find module ‘webpack’

This error occurs when you don’t have the webpack package installed properly on your computer.

To install the webpack package, you need to use the npm install command:

npm install --save-dev webpack

The command above will install the webpack package locally. If you want to install the package globally instead, you need to add the --global flag:

npm install --global webpack

But this is not recommended because you will be forced to use the same webpack version for all projects you have on your computer.

It’s better to install the package locally for each project as a dev dependency using the --save-dev option.

When you have the package installed, the error should be resolved.

2. Cannot find module ‘webpack-cli’

This error occurs when you try to run the webpack-cli module, but you don’t have the package installed.

To resolve this error, you need to install the webpack-cli package as follows:

# locally
npm install --save-dev webpack webpack-cli

# globally
npm install --global webpack webpack-cli

Make sure that you also install the webpack package, or you will have the “Cannot find module ‘webpack’” error.

Here, you can choose to install the modules locally or globally. The recommended option is to install the modules locally, so you can have different webpack versions for each project.

3. Cannot find module ‘webpack/bin/config-yargs’

This error usually occurs when you use webpack version 4 or 5, and you run the webpack-dev-server command to activate the webpack development server.

Here’s an example package.json file that may cause the error:

  "scripts": {
    "dev": "webpack-dev-server --mode development --env development"

When you run the npm start dev command, the following error happens:

throw err;

Error: Cannot find module 'webpack/bin/config-yargs'

This is because webpack changed the command to run the development server from webpack-dev-server to webpack serve.

You need to change the command in your package.json file as follows:

  "scripts": {
    "dev": "webpack serve --mode development --env development"

Now you can try to run the command again. This time it should work.

I hope this guide helps you solve errors related to the webpack module in your project. Happy coding! 🙌

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.