1.0.2 • Published 1 year ago
node-module-type v1.0.2
node-module-type
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.jsonwith"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.jsonwith"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)modulecommonjs
1.0.2
1 year ago
1.0.1
1 year ago
1.0.0
1 year ago
1.0.0-rc.1
1 year ago
1.0.0-rc.0
1 year ago
1.0.0-alpha.1
1 year ago