esm-utils

Utilities you'll need when migrating to ESModule.

Usage no npm install needed!

<script type="module">
  import esmUtils from 'https://cdn.skypack.dev/esm-utils';
</script>

README

esm-utils

Build Status Coverage Npm Version MIT License

Utilities you'll need when migrating to ESModule.

Install

yarn add esm-utils

Usage

import createEsmUtils from 'esm-utils'

const {
  require,
  dirname,
  filename,
  readJson,
  readJsonSync,
  importModule,
} = createEsmUtils(import.meta)

API

createEsmUtils(import.meta | URL | 'string')

Returns an object with the following properties:

  • dirname (alias __dirname)
  • filename (alias __filename)
  • require
  • importModule (alias import)
  • readJson (alias loadJson)
  • readJsonSync (alias loadJsonSync)

Please read this note before you use dirname and filename

Sync version of readJson.

json

  • json.{read,load} alias of readJson
  • json.{read,load}Sync alias of readJsonSync

importModule(string | URL)

Same as import(), but accepts absolute path (on Windows, import('C:\\foo.js') error throws when pass a absolute path starts with a drive letter).

readJson(string | URL)

Returns Promise<jsonObject>.

readJsonSync(string | URL)

Import json file

With Import Assertions

import foo from './foo.json' assert {type: 'json'}
await import('./foo.json', {assert: {type: 'json'}})

With require, like CommonJS

import createEsmUtils from 'esm-utils'

const {require} = createEsmUtils(import.meta)
const foo = require('./foo.json')

With readJson or readJsonSync

import createEsmUtils from 'esm-utils'

const {readJson} = createEsmUtils(import.meta)
const foo = await readJson('./foo.json')
import createEsmUtils from 'esm-utils'

const {readJsonSync} = createEsmUtils(import.meta)
const foo = readJsonSync('./foo.json')

You don't need dirname and filename

The dirname and filename supposed to be a quick solution when migrating to ES Modules. In most cases, you don't need them, because many APIs accept URL directly.

/* BAD */
import fs from 'node:fs/promises'
import path from 'node:path'
import createEsmUtils from 'esm-utils'

const {dirname} = createEsmUtils(import.meta)
const buffer = await fs.readFile(
  path.join(dirname, './path/to/file')
)
/* GOOD */
import fs from 'node:fs/promises'

const buffer = await fs.readFile(
  new URL('./path/to/file', import.meta.url)
)