如何为npm scoped作用域包配置自定义TypeScript类型声明
解决方案
1. 调整tsconfig配置
在compilerOptions中新增typeRoots配置,显式指定TypeScript查找类型定义的目录,修改后配置如下:
{ "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "baseUrl": "src", "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "noFallthroughCasesInSwitch": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", // 新增以下配置 "typeRoots": ["src/types", "node_modules/@types"] }, "include": [ "src" ] }
2. 确认类型文件规则
- 类型文件路径使用
src/types/@example-org/react-date-range/index.d.ts即可,不需要使用双下划线命名格式。 - 如果类型文件中没有任何顶层的
import/export语句,直接写模块声明即可:
declare module "@example-org/react-date-range" { // 复用你之前写的所有react-date-range类型定义即可 }
- 如果类型文件中需要导入其他类型(比如React的类型),需要把模块声明包在
declare global块中,避免全局声明失效:
import type { ReactNode } from "react"; declare global { declare module "@example-org/react-date-range" { // 你的类型定义 } // 如果有导入子模块的需求(比如导入包内的样式),可以补充对应声明 declare module "@example-org/react-date-range/dist/*.css" {} }
3. 生效验证
修改完成后执行以下操作清除缓存:
- 删除本地缓存目录:
rm -rf node_modules/.cache - 如果你使用VSCode开发,按
Ctrl+Shift+P(Mac为Cmd+Shift+P),选择TypeScript: Restart TS Server重启语言服务即可。
内容的提问来源于stack exchange,提问作者Hugo Licón
相关产品推荐
相关产品推荐

