Skip to content

Differences between ES modules and CommonJS:

  1. No require, exports, or module.exports

  2. No __filename or __dirname

  3. No Addon Loading

  4. No require.resolve

  5. No NODE_PATH

  6. No require.extensions

  7. No require.cach

1.import

import 导入的方式:

  1. file URLS
js
import './test.mjs?query=1' // loads ./test.mjs with query of "?query=1"
  1. data imports
  • text/javascript for ES modules
  • application/json for JSON
  • application/wasm for Wasm
  1. node imports
js
import fs from 'node:fs/promises'
js
import './test.mjs?query=1'

import 'data:text/javascript,console.log("hello!")'
// import _ from 'data:application/json,"world!"' with { type: 'json' }

2.import.meta

  1. import.meta.url 当前文件的绝对路径

  2. import.meta.resolve 获取模块的绝对路径(类似于 path.resolve, 但该 API 依赖较高的 node 版本)

https://nodejs.org/docs/latest/api/esm.html#importmetaresolvespecifier

js
const dependencyAsset = import.meta.resolve('component-lib/asset.css');
// file:///app/node_modules/component-lib/asset.css
import.meta.resolve('./dep.js');
// file:///app/dep.js

在目前的版本中,如果要获取 __dirname,可以使用:

js
const _dirname = path.dirname(url.fileURLToPath(import.meta.url))
js
console.log(import.meta)

// __dirname is not defined in ES module scope
// import path from 'node:path'
// console.log(path.resolve(__dirname, './1.import.meta.mjs'))

import { fileURLToPath } from 'url'
import { dirname } from 'path'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
console.log(__dirname) // Logs the directory name of the current module

3.await

cjs
// await is only valid in async functions and the top level bodies of modules
const five = await Promise.resolve(5)
mjs
/*
Top-level await:

在ES模块中,await可以在顶层使用。
*/

// works
export const five = await Promise.resolve(5)

/*
If a top level await expression never resolves, the node process will exit with a 13 status code.

[status code](https://nodejs.org/docs/latest/api/process.html#exit-codes)
*/
import { spawn } from 'node:child_process'
import { execPath } from 'node:process'
spawn(execPath, [
  '--input-type=module',
  '--eval',
  // Never-resolving Promise:
  'await new Promise(() => {})',
]).once('exit', (code) => {
  console.log(code) // Logs `13`
})