Debug

Node.js Debug

Module

Error [ERR_MODULE_NOT_FOUND]: Cannot find module in JS

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

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

// package.json

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

2. Specify the extension when importing local files

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

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.

3. Specify a relative path when importing local files

Another common cause of the error is specifying a relative path incorrectly.

// index.js
// ⛔️ 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 '../'.

// index.js

// ✅ import from 1 directory up
import {sum} from '../another-file.js';

// ✅ import from 2 directories up
import {sum} from '../../another-file.js';

4. Don’t use the 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.

package.json
{
  "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.

File

Fix the “__dirname is not defined in ES module scope” Error in JavaScript.

Create utility for __dirname and __filename

// file-dir-name.js

import { fileURLToPath } from 'url';
import { dirname } from 'path';

export default function fileDirName(meta) {
  const __filename = fileURLToPath(meta.url);

  const __dirname = dirname(__filename);

  return { __dirname, __filename };
}

We’ll be able to use this utility across the various other module files in our project.

// index.js
import fileDirName from './file-dir-name.js';

const { __dirname, __filename } = fileDirName(import.meta);

console.log(__dirname);

console.log(__filename);

Reference