Skip to content

Detect if a Node.js file is executed as an ES module or CommonJS.

License

Notifications You must be signed in to change notification settings

morganney/module-type

Repository files navigation

CI codecov NPM version

Detects if a Node.js file is executed as an ES module or CommonJS.

Requirements

  • Node.js >= 20.11.0

Example

If the project has:

  • package.json with "type": "module"
  • Uses file extensions of .mjs
  • Started node with --experimental-default-type=module

Then:

import { moduleType } from 'node-module-type'

console.log(moduleType()) // 'module'

If the project instead has:

  • package.json with "type": "commonjs" (or omitted)
  • Uses file extensions of .cjs
  • Started node with --experimental-default-type=commonjs

Then:

const { moduleType } = require('node-module-type')

console.log(moduleType()) // 'commonjs'

This is all pretty obvious based on how node-module-type was loaded by the consuming package, however, library authors publishing a dual package can provide conditional logic based on what module system your code is running under.

For example, when using TypeScript that compiles to different module systems where detection is based on the module and nearest package.json type values.

import { moduleType } from 'node-module-type'

const type = moduleType()

if (type === 'commonjs') {
  // Code running under CommonJS module scope
  import('some-cjs-dependency').then().catch()
}

if (type === 'module') {
  // Code running under ES module scope
  import('some-esm-dependency').then().catch()
}

See the tslib test for a more comprehensive example.

Output

node-module-type and the corresponding exported function moduleType produce three possible output strings:

  • unknown (only if something unexpected happens)
  • module
  • commonjs