Skip to content

Instantly share code, notes, and snippets.

@mkg20001
Last active August 31, 2021 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkg20001/59b74ea2bd1ae66fc904d9422785e94e to your computer and use it in GitHub Desktop.
Save mkg20001/59b74ea2bd1ae66fc904d9422785e94e to your computer and use it in GitHub Desktop.
Common things from CJS brought to ESM
/*
NOTE:
- The metadata of the current module "module" in ESM is under "import.meta"
- Dynamic import is always async, meaning you need to await it
- Also if you export default it's under .default, no longer returned directly
*/
// dirname
import { dirname } from 'path'
import { fileURLToPath } from 'url'
const __dirname = dirname(fileURLToPath(import.meta.url))
// require
async function require (thing) {
const imported = await import(thing) // "dynamic import"
return Object.assign(imported.default || {}, imported)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment