Skip to content

ESM

Pure ES module

Create ESM package

  1. Config below in package.json:
json
{
  "type": "module"
}
  1. use import foobar from 'foobar' instead of require.

  2. NodeJS require >=12.20 | >=14.14 | >=16.0. Recommended { "engines": { "node": ">=14.16" } }.

  3. Replace { "main": "index.js" } with { "exports": "./index.js" }.

  4. Use full relative path for imports with file ext.

  5. Recommended use node: protocol for import.

  6. 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))

__filename

Refs

CC BY-NC 4.0