启用moduleResolution: bundler时无法导入模块A的技术问题
模块B使用bundler模式导入模块A的类型解析错误原因及修复
背景信息
模块B的tsconfig.json配置:
{ "compilerOptions": { "strict": true, "module": "esnext", "moduleResolution": "bundler", } }
导入模块A时触发的错误提示:
Could not find a declaration file for module 'moduleA'. 'node_modules/moduleA/index.mjs' implicitly has an 'any' type.
There are types at 'node_modules/moduleA/index.d.ts', but this result could not be resolved when respecting package.json "exports". The 'moduleA' library may need to update its package.json or typings.
模块A的package.json配置:
{ "name": "ModuleA", "version": "1.0.0", "main": "index.mjs", "module": "index.mjs", "types": "index.d.ts", "type": "module", "files": [ "index.cjs", "index.mjs", "index.d.ts" ], "exports": { ".": { "import": { "types": "./index.d.ts", "default": "./index.mjs" }, "require": { "types": "./index.d.ts", "default": "./index.cjs" } } }, "engines": { "node": ">=18.0.0" }, "scripts": { "test": "echo \"Error: no test specified\" && exit 1" } }
模块A的index.d.ts结构:
type A = { someField: someType; // ... }; type B = { someOtherField: someType; // ... }; // 更多类型定义 export { A, B // 更多导出类型 };
问题原因
moduleResolution: "bundler"模式下,TypeScript对package.json的exports字段解析逻辑和node模式存在关键差异:
- bundler模式要求
types字段处于条件顶层:该模式严格遵循ES模块规范的导出解析逻辑,期望类型声明路径直接挂载在import/require这类条件的顶层,而非嵌套在子对象中。当前模块A的exports配置将types放在import和require的子属性里,不符合bundler模式的解析规则。 - node模式兼容旧写法:
node模式的解析逻辑更宽松,会自动回退读取根级types字段,或者识别exports中嵌套的types配置,因此不会出现类型找不到的问题。
修复方案
调整模块A的package.json中exports字段的结构,将types提升到对应条件的顶层即可:
"exports": { ".": { "import": "./index.mjs", "require": "./index.cjs", "types": "./index.d.ts" } }
如果需要为不同导入方式单独配置其他属性(当前场景不需要),也可以采用如下写法:
"exports": { ".": { "import": { "default": "./index.mjs" }, "require": { "default": "./index.cjs" }, "types": "./index.d.ts" } }
内容的提问来源于stack exchange,提问作者user20986640
相关产品推荐
相关产品推荐

