Angular 18导入ESM格式本地TS库失败,需转CJS吗?
Angular 18兼容ESM格式本地库的正确姿势
不用局限于CJS
完全没必要只用CJS格式打包,ESM可以完美兼容Angular 18,你之前遇到的“找不到库”问题,核心是库的打包配置和package.json入口声明没跟上规范。
你的临时重命名方案是合理的
把.d.mts改成.d.ts的思路没问题,这和Angular官方库的配置逻辑一致——本质是让TypeScript能精准找到类型文件,同时保证ESM模块的入口路径正确。不过不用手动改,通过配置就能自动生成对应文件。
一步到位的配置方法
1. 调整tsup打包配置
修改tsup.config.ts,让打包时直接生成.d.ts类型文件,而非.d.mts:
import { defineConfig } from 'tsup'; export default defineConfig({ entry: ['src/index.ts'], format: ['esm'], outDir: 'dist', dts: { resolve: true, outputExtension: '.d.ts' // 指定类型文件后缀为.d.ts }, sourcemap: true, clean: true });
2. 完善库的package.json
必须明确声明模块类型和入口路径,参考Angular官方库的配置结构:
{ "name": "your-local-library", "version": "1.0.0", "type": "module", // 标记当前库为ESM模块 "main": "./dist/index.mjs", "module": "./dist/index.mjs", "types": "./dist/index.d.ts", "exports": { ".": { "types": "./dist/index.d.ts", "esm2022": "./dist/index.mjs", "esm": "./dist/index.mjs", "default": "./dist/index.mjs" } } }
报错原因解析
Angular 18本身是基于ESM构建的,但TypeScript解析.d.mts时,要求库的package.json要么声明"type": "module",要么在类型入口里明确指向.d.mts文件。如果你的库没正确配置exports字段或类型路径,Angular的构建工具(Vite/webpack)就无法正确识别模块和类型,从而抛出“找不到库”的错误。
验证步骤
配置完成后重新打包库,在Angular项目里通过本地依赖(比如"your-local-library": "file:../your-library-path")或npm link导入,启动项目即可正常使用。
内容的提问来源于stack exchange,提问作者C. Leroy
相关产品推荐
相关产品推荐

