Error [ERR_MODULE_NOT_FOUND]: Cannot find module in JS

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Error [ERR_MODULE_NOT_FOUND]: Cannot find module in JS #

The "Error [ERR_MODULE_NOT_FOUND]: Cannot find module" occurs when you set the type attribute to module in your package.json file, but omit the file extension when importing. To solve the error, specify the extension when importing local files.

error module not found cannot find module

Here is an example of how the error occurs.

index.js
// ⛔️ Error [ERR_MODULE_NOT_FOUND]: Cannot find module // imported from ... Did you mean to import import {sum} from './another-file'; console.log(sum(10, 10)); // 👉️ 20

The package.json file has the type attribute set to module.

package.json
{ "type": "module", // ... rest }

To solve the error, make sure to include the extension when importing local files with type set to module in your Node.js project.

index.js
// 👇️ Node: .js extension specified import {sum} from './another-file.js'; console.log(sum(10, 10)); // 👉️ 20

The node docs state that a file extension must be provided when using the import keyword to resolve relative or absolute specifiers.

This behavior matches how import works in browser environments.

Directory specifiers like ./my-folder/my-file.js must also be fully specified.

Another thing to look out for is that when using ES6 module imports with type set to module, you are not allowed to use the require syntax anymore.

If you have any imports in your codebase that use require, convert them to ES6 modules import syntax.

If you try to use require in an ES6 modules project, you'd get the error: "ReferenceError: require is not defined in ES module scope, you can use import instead".

Conclusion #

The "Error [ERR_MODULE_NOT_FOUND]: Cannot find module" occurs when you set the type attribute to module in your package.json file, but omit the file extension when importing. To solve the error, specify the extension when importing local files.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.