package.json中exports配置的types路径无法导入问题排查
React组件库
library/types导入错误排查方案 问题说明
使用Vite+Rollup构建React组件库,已在package.json中配置三个导出入口:.、./index.css、./types,其中前两个可正常通过import { Component } from "library"和import "library/index.css"导入,但执行import type { Type } from "library/types"时出现错误:
Cannot find module 'library/types' or its corresponding type declarations.
仅当将types文件夹放在项目根目录时,该导入才能正常工作。
现有配置信息
package.json 导出配置
"exports": { ".": { "import": "./dist/library.es.js", "require": "./dist/library.umd.js", "types": "./dist/index.d.ts" }, "./types": { "import": "./dist/types.d.ts", "require": "./dist/types.d.ts", "types": "./dist/types.d.ts" }, "./index.css": { "import": "./dist/index.css", "require": "./dist/index.css" } }
项目文件夹结构
|-package.json |-src |-dist | |-index.d.ts | |-library.es.js | |-library.umd.js | |-types.d.ts | |-index.css
排查与解决步骤
1. 确认TypeScript模块解析模式
TypeScript对package.json的exports字段支持依赖正确的模块解析模式,需在tsconfig.json的compilerOptions中设置:
"moduleResolution": "NodeNext", "module": "NodeNext"
若使用较旧版本TypeScript,可改用Node16,确保TS能正确识别exports中的类型入口。
2. 验证dist/types.d.ts的正确性
- 检查
dist/types.d.ts是否存在,且文件内是否正确导出所需类型,示例:export type Type = { /* 类型定义内容 */ }; - 确认Rollup/Vite的构建配置是否将src中的类型文件(如
src/types/index.ts)正确编译并输出到dist/types.d.ts,避免遗漏类型导出。
3. 配置开发环境路径映射(本地调试场景)
如果是在本地通过npm link或直接引用组件库调试,需在项目的tsconfig.json中添加路径映射,确保TS能找到类型文件:
"compilerOptions": { // ...其他配置 "paths": { "library": ["./path-to-library/dist"], "library/types": ["./path-to-library/dist/types.d.ts"] } }
4. 补充typesVersions兼容配置(可选)
若需兼容v4.7以下版本的TypeScript,可在package.json中添加typesVersions字段兜底类型解析:
"typesVersions": { "*": { "types": ["./dist/types.d.ts"] } }
5. 检查package.json字段冲突
确保package.json中没有其他影响类型解析的字段,比如若types字段指向根目录的类型文件,会覆盖exports配置,需删除或调整为指向dist/index.d.ts。
内容的提问来源于stack exchange,提问作者JulSeb42
相关产品推荐
相关产品推荐

