Last updated: Mar 6, 2024
Reading timeยท2 min
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.
Here is an example of how the error occurs.
// โ๏ธ 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
.
{ "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.
// ๐๏ธ Node: .js extension specified import {sum} from './another-file.js'; console.log(sum(10, 10)); // ๐๏ธ 20
Note that we added the .js
extension in the file name.
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 common cause of the error is specifying a relative path incorrectly.
// โ๏ธ incorrect import import {sum} from '.another-file.js'; // โ correct import import {sum} from './another-file.js';
Notice that we forgot to specify the forward slash in the first import statement.
If you need to import from one directory up, start your import with '../'
.
// โ import from 1 directory up import {sum} from '../another-file.js'; // โ import from 2 directories up import {sum} from '../../another-file.js';
require()
syntax with type
set to module
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.
{ "type": "module", // ... rest }
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".
If you'd rather use the require
syntax, you have to remove the type
attribute from your package.json
file.
You can learn more about the related topics by checking out the following tutorials: