Skip to content

Instantly share code, notes, and snippets.

@cmdcolin
Created February 24, 2025 05:22
Show Gist options
  • Save cmdcolin/c3089a4b37f2ff8c8eabce5ebd3b4082 to your computer and use it in GitHub Desktop.
Save cmdcolin/c3089a4b37f2ff8c8eabce5ebd3b4082 to your computer and use it in GitHub Desktop.
If you want to publish ESM/CJS you can update your package.json to use the
"exports" field, and run the tsc compiler twice over the code, once using
--module cjs
```json
{
"name": "dualpackage",
"version": "1.0.0",
"description": "demo of dual esm/cjs package",
"type": "module",
"types": "./cjs/index.d.ts",
"exports": {
"import": {
"import": "./esm/index.js"
},
"require": {
"require": "./cjs/index.js"
}
},
"scripts": {
"clean": "rimraf cjs",
"prebuild": "yarn clean",
"preversion": "yarn build",
"postversion": "git push --follow-tags",
"build:esm": "tsc --outDir esm",
"build:cjs": "tsc --module commonjs --outDir cjs",
"postbuild:cjs": "echo '{\"type\": \"commonjs\"}' > cjs/package.json",
"build": "yarn build:esm && yarn build:cjs"
},
"devDependencies": {
"rimraf": "^6.0.1",
"typescript": "^5.7.3"
}
}
```
Note that postbuild:cjs (which is automatically run after any invocation of
build:cjs) outputs a "one line" **extra** package.json to the cjs folder that
says type:cjs specifically in the cjs distribution (credit:
https://evertpot.com/universal-cjs-esm-typescript-packages/).
You can alternatively name the all the files in the cjs folder with the .cjs
file extension, which node will recognize as being commonjs and not ESM module
files, if you do not want to use the one-line-package.json-with-type:cjs trick,
but the tsc compiler does not currently have an option to output the .cjs file
extension natively
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment