@jjuidev/esm-package-json
v1.0.3
Published
A utility package for working with ESM package.json files
Maintainers
Readme
@jjuidev/esm-package-json
A utility CLI tool that automatically generates a minimal package.json file with "type": "module" in your dist/esm folder to ensure proper ESM module resolution.
Installation
Global Installation (Recommended)
npm install -g @jjuidev/esm-package-jsonLocal Installation
npm install --save-dev @jjuidev/esm-package-jsonUsage
CLI Usage
After building your TypeScript project, run:
esm-package-jsonOr specify a custom dist folder:
esm-package-json --dist ./build
esm-package-json -d ./outputWhat it does
This tool scans your dist folder and:
- Looks for an
esmsubdirectory - Creates a
package.jsonfile inside theesmfolder if it doesn't exist - The generated
package.jsoncontains:{"type": "module"}
This ensures that your ESM modules are properly recognized by Node.js and bundlers.
Example
Given this project structure:
your-project/
├── dist/
│ ├── cjs/
│ │ └── index.cjs
│ └── esm/
│ └── index.js
└── package.jsonRunning esm-package-json will create:
your-project/
├── dist/
│ ├── cjs/
│ │ └── index.cjs
│ └── esm/
│ ├── index.js
│ └── package.json ← Generated with {"type": "module"}
└── package.jsonOptions
| Option | Alias | Description | Default |
| -------- | ----- | ---------------------------- | -------- |
| --dist | -d | Specify the dist folder path | ./dist |
Integration with Build Tools
With tsup
Add to your package.json scripts:
{
"scripts": {
"build": "tsup",
"postbuild": "esm-package-json"
}
}With npm scripts
{
"scripts": {
"build": "tsc && esm-package-json",
"build:watch": "tsc --watch & esm-package-json --dist ./dist"
}
}Why do you need this?
When building dual-package libraries (both CommonJS and ESM), you often have separate output folders:
dist/cjs/for CommonJS filesdist/esm/for ESM files
Node.js determines module type based on the nearest package.json file. Without a package.json with "type": "module" in the ESM folder, Node.js might not correctly identify your ESM modules, leading to import/export issues.
Requirements
- Node.js >= 16.0.0
Repository
- GitHub: https://github.com/jjuidev/esm-package-json
- Issues: https://github.com/jjuidev/esm-package-json/issues
License
MIT © jjuidev
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Changelog
1.0.0
- Initial release
- CLI tool to generate ESM package.json files
- Support for custom dist folder paths
