Is it possible to configure my package.json to support different imports for CJS and ESM formats?
"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
In addition, can I set up my TypeScript compiler to generate two distributions:
// for ESM
{
"compilerOptions": {
"module": "es2020",
"target": "es2015",
"declaration": true,
"esModuleInterop": true,
"moduleResolution": "node",
"forceConsistentCasingInFileNames": true,
"outDir": "./dist/esm"
},
"include": [
"src/**/*"
]
}
// for CJS
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "CommonJS",
"outDir": "./dist/cjs"
},
By running both configurations through tsc, a dist folder containing both the cjs
and esm
folders can be created:
"build": "tsc -p tsconfig.json && tsc -p tsconfig-cjs.json"
However, the testing reveals that I need to add .default
in both examples:
// CJS
const someClass = require('package').default
const instance = new someClass()
// ESM
import someClass from 'package'
const instance = new someClass.default("")
How can I eliminate the requirement of adding .default
in both instances?
The package exports just a single class:
import someClass from './class';
export default someClass;
This is how the class is defined:
class someClass { constructor() {} }
export default someClass