Skip to content

Node.js tool for updating your ES module and CommonJS specifiers.

License

Notifications You must be signed in to change notification settings

knightedcodemonkey/specifier

Repository files navigation

CI codecov NPM version

Node.js tool for parsing imports to change ESM and CJS specifiers.

  • Rewrite specifier values.
  • Updates files or strings.
  • Read metadata about a specifier's AST node.
  • Parses import, import(), import.meta.resolve(), export, require, and require.resolve().

Example

Given a file with some imports and exports:

// file.ts

import { someLib } from 'some-package'
import { foo } from './path/to/foo.js'

export { bar } from './path/to/bar.js'

You can use specifier to change the values:

import { specifier } from '@knighted/specifier'

const update = await specifier.update('file.ts', ({ value }) => {
  if (value === 'some-package') {
    return 'some-package/esm'
  }

  return value.replace('.js', '.mjs')
})

console.log(update)

/*
import { someLib } from 'some-package/esm'
import { foo } from './path/to/foo.mjs'

export { bar } from './path/to/bar.mjs'
*/

Or collect the AST nodes:

import { type Spec, specifier } from '@knighted/specifier'

const nodes: { node: Spec['node']; parent: Spec['parent'] }[] = []

await specifier.update('file.ts', ({ parent, node }) => {
  nodes.push({ node, parent })
})

nodes.forEach(({ node, parent }) => {
  // Do something with the metadata
})