Transform typescript output to
.mjs
and.cjs
compatible code. One codebase to rule them all.
This simple utility will ensure you deliver packages using latest ES standards. It relies on two separate typescript tsconfig.json configurations to generate esnext
and commonjs
modules. After build, mjscjs
will process all the generated files:
✅ Renames all your files to .mjs
and .cjs
respectively
✅ Renames all your sourcemaps to .mjs.map
and .cjs.map
✅ Replaces all your imports to use .mjs
and requires to use .cjs
✅ Replaces all your sourcemap references
✅ Replaces all your tsconfig.json paths aliases with relative imports and requires
npm install -D mjscjs
For mjscjs
to work properly, please make sure your tsconfig.json specifies the following configuration options:
{
"compilerOptions": {
"outDir": "lib",
"rootDir": "./src",
"baseUrl": ".",
"paths": {
"@example/*": ["./src/*"]
}
}
}
Create a file called tsconfig.mjs.json.
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "esnext",
"outDir": "lib-mjs"
}
}
Create a file called tsconfig.cjs.json.
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs",
"outDir": "lib-cjs"
}
}
When working with a typescript project, simply target the tsconfig.json file of your project.
npx tsc -d -p tsconfig.mjs.json
npx mjscjs -p tsconfig.mjs.json
npx tsc -d -p tsconfig.cjs.json
npx mjscjs -p tsconfig.cjs.json
To make things easier, add mjscjs
to your package.json scripts and run the complete build using npm run build
.
{
"scripts": {
"build": "npm run build:mjs && npm run build:cjs",
"build:mjs": "tsc -d -p tsconfig.mjs.json && npm run build:mjs:transform",
"build:mjs:transform": "mjscjs -p tsconfig.mjs.json",
"build:cjs": "tsc -d -p tsconfig.cjs.json && npm run build:cjs:transform",
"build:cjs:transform": "mjscjs -p tsconfig.cjs.json"
}
}
Attention The non-typescript usage is work in progress and not properly tested. Contributions are welcome.
When working with a non-typescript project, you can specify the module type, build dir, and source dir separately.
npx mjscjs --target . --buildDir './build' --srcDir './src' --module esm
npx mjscjs -t . -b './build' -s './src' -m esm
Contributions are welcome! Please raise an issue to discuss any problem or feature request.
Code copyright 2022 Alex Grozav. Code released under the MIT License.