ESM
Pure ES module
Create ESM package
- Config below in
package.json
:
json
{
"type": "module"
}
use
import foobar from 'foobar'
instead ofrequire
.NodeJS require
>=12.20 | >=14.14 | >=16.0
. Recommended{ "engines": { "node": ">=14.16" } }
.Replace
{ "main": "index.js" }
with{ "exports": "./index.js" }
.Use full relative path for imports with file ext.
Recommended use
node:
protocol for import.For TypeScript project, set
"module": "node16"
and"moduleResolution": "node16"
.
require.resolve
js
import { createRequire } from 'node:module'
const require = createRequire(import.meta.url)
const vue = require.resolve('vue')
__dirname
js
import path, { dirname } from 'node:path'
import { fileURLToPath, URL } from 'node:url'
// Both esm and cjs
const __dirname = fileURLToPath(new URL('.', import.meta.url))
const __filename = fileURLToPath(import.meta.url)
// const __dirname = path.dirname(fileURLToPath(import.meta.url))
// const __dirname = __dirname !== undefined ? __dirname : dirname(fileURLToPath(import.meta.url))