Lerna Monorepo中TypeScript核心库开发模块引用问题求助
Great question! You don't have to hack your main field or manually swap it before publishing—TypeScript (and tools like IntelliJ/TSLint) support standard package.json fields that let you point to your source files for development while keeping compiled JS for production. Here's how to set it up:
1. Use the exports Field (Modern Recommended Approach)
TypeScript 4.7+ supports the exports field in package.json, which lets you define entry points for different environments (including TypeScript type resolution). This is the cleanest solution because it's standardized and works with both tooling and runtime.
Update your core library's package.json to include:
"main": "dist/cjs/index.js", "module": "dist/esm/index.js", "es2015": "dist/es2015/index.js", "types": "dist/es2015/index.d.ts", "exports": { ".": { "types": "./src/index.ts", "import": "./dist/esm/index.js", "require": "./dist/cjs/index.js", "default": "./dist/cjs/index.js" } }
How this works:
- TypeScript/IntelliJ/TSLint: Will prioritize the
typesentry inexports, which points directly to your sourcesrc/index.ts. This eliminates the "module missing" errors because the tools can now find the original TypeScript files. - Node.js/Browsers: Will use the
importorrequireentries based on the module system, loading the compiled JS fromdistas expected. - Backward Compatibility: The existing
main/modulefields are still there for older tools that don't supportexports.
Requirements:
- Ensure your TypeScript version is 4.7 or higher.
- In your consumer packages'
tsconfig.json, setmoduleResolutionto"node16"or"nodenext"(this tells TypeScript to respect theexportsfield's resolution rules).
2. Alternative: Use typesVersions (Older TypeScript Versions)
If you're stuck on an older TypeScript version (pre-4.7), you can use the typesVersions field to map type resolution to your source files. Add this to your core library's package.json:
"types": "dist/es2015/index.d.ts", "typesVersions": { "*": { "*": ["src/*"] } }
This tells TypeScript that for any version of TypeScript (*), when resolving types for any path (*), it should look in the src directory first instead of dist. IntelliJ and TSLint will pick up this mapping automatically.
Why This Beats Your Original Workaround
Both approaches avoid:
- Manually swapping
mainbetweensrcanddistbefore publishing. - Needing to compile TypeScript constantly during development—you can work directly with source files and only compile when you're ready to publish.
Just make sure when you publish your core library, the dist directory is included in your npm package (via the files field in package.json, e.g., "files": ["dist", "src"] if you want to include source for debugging, or just "dist" if not).
内容的提问来源于stack exchange,提问作者Kai Sellgren

