Differences between ES modules and CommonJS:
No require, exports, or module.exports
No __filename or __dirname
No Addon Loading
No require.resolve
No NODE_PATH
No require.extensions
No require.cach
1.import
import
导入的方式:
file URLS
js
import './test.mjs?query=1' // loads ./test.mjs with query of "?query=1"
data imports
text/javascript
forES modules
application/json
forJSON
application/wasm
forWasm
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
import.meta.url
当前文件的绝对路径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`
})