← Back to Node.js, page 7

nodejs-0127 · Easy fresher

How does Node.js resolve ES module imports compared with require: file extensions, directories, JSON and import.meta?

ES module imports need the full file name with extension, and directory imports do not work, unlike require. JSON needs an import attribute (with { type: 'json' }). import.meta.url, import.meta.dirname, import.meta.filename and import.meta.resolve replace __dirname and require.resolve. Top-level await is allowed, and require() can load an ES module if it has no top-level await.

Full answer

Differences between CommonJS and ESM resolution:

  • Extensions: require('./util') tries .js, .json, .node and index files. import './util.js' must include the extension. Without it you get ERR_MODULE_NOT_FOUND.
  • Directories: require('./lib') loads ./lib/index.js. import './lib' fails with ERR_UNSUPPORTED_DIR_IMPORT. Import './lib/index.js' or add a package.json exports map.
  • Specifiers are URLs: './file.js', '/abs/path', 'file:///path', 'node:fs', 'data:' and bare package names. Query strings make different module instances (import './a.js?v=2').
  • JSON: import data from './data.json' with { type: 'json' }. The attribute is required. The older assert keyword was removed, use with.
  • Static imports are hoisted and loaded before the module body runs. Use dynamic import() for conditional or lazy loading. It returns a promise and also works in CommonJS.

Replacements for CommonJS globals:

  • import.meta.url: the file URL of this module.
  • import.meta.dirname and import.meta.filename: available in current Node versions.
  • import.meta.resolve('./util.js'): gives the resolved URL, like require.resolve.
  • No __dirname, __filename, require, module or exports. Use createRequire(import.meta.url) when you need require.

Other facts:

  • The default export of a CommonJS module is its module.exports. Named imports from CommonJS work only if Node can detect them statically.
  • Top-level await works in ES modules.
  • Module files are cached by URL, and ES modules are always in strict mode.
  • Use .mjs or "type": "module" in package.json to mark files as ESM.
javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawnSync } = require('node:child_process');

const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'esm-'));
fs.mkdirSync(path.join(dir, 'lib'));
fs.writeFileSync(path.join(dir, 'util.js'), 'export const hello = "hello from util";');
fs.writeFileSync(path.join(dir, 'lib', 'index.js'), 'export const lib = true;');
fs.writeFileSync(path.join(dir, 'data.json'), '{"course":"Node.js"}');
fs.writeFileSync(path.join(dir, 'package.json'), '{"type":"module"}');
fs.writeFileSync(path.join(dir, 'main.js'), `
import { hello } from './util.js';
import data from './data.json' with { type: 'json' };
console.log(hello, '|', data.course);
console.log('dirname ends with the folder name:', import.meta.dirname.endsWith('${path.basename(dir)}'));
console.log('filename:', import.meta.filename.endsWith('main.js'));
console.log('resolve:', import.meta.resolve('./util.js').startsWith('file://'));
for (const spec of ['./util', './lib']) {
  try { await import(spec); } catch (err) { console.log('import', spec, '->', err.code); }
}
console.log('typeof require:', typeof require, '| typeof __dirname:', typeof __dirname);
const value = await Promise.resolve('top-level await works');
console.log(value);
`);

const run = spawnSync(process.execPath, ['main.js'], { cwd: dir, encoding: 'utf8' });
process.stdout.write(run.stdout);
if (run.status !== 0) console.log(run.stderr);
fs.rmSync(dir, { recursive: true });

A temporary ES module project imports a file, a JSON file, a missing extension and a directory, and prints what import.meta provides. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): hello from util | Node.js dirname ends with the folder name: true filename: true resolve: true import ./util -> ERR_MODULE_NOT_FOUND import ./lib -> ERR_UNSUPPORTED_DIR_IMPORT typeof require: undefined | typeof __dirname: undefined top-level await works

Key points

  • ESM imports need explicit extensions and cannot import directories.
  • JSON imports need with { type: 'json' }.
  • import.meta replaces __dirname, __filename and require.resolve.
  • Dynamic import() works in both module systems.
  • createRequire gives you require inside ESM.

Common mistakes

  • Leaving out the .js extension in a relative import.
  • Importing a directory and expecting index.js.
  • Importing JSON without the type attribute.
  • Using __dirname in an ES module.
  • Expecting named imports from every CommonJS package.

Follow-ups

  • What does import() do inside a CommonJS file?
  • How do you get require in an ES module?
  • What is a file URL, and why does ESM use URLs?

Tips

  • List the four differences: extension, directory, JSON, globals.
  • Name import.meta.dirname.
  • Say that import() works in CommonJS too.