Error [ERR_MODULE_NOT_FOUND]: Cannot find module in JS

avatar

Borislav Hadzhiev

Tue Mar 15 20221 min read

banner

Photo by Randy Jacob

Error [ERR_MODULE_NOT_FOUND]: Cannot find module in JS #

The "Error [ERR_MODULE_NOT_FOUND]: Cannot find module" occurs when you have set the type attribute to module in your package.json file, but have omitted the file extension when importing. To solve the error, provide 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

And 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 the type attribute 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 lookout for is - 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".

Use the search field on my Home Page to filter through my more than 1,000 articles.