如何配置让tsc识别node_modules中uhtml的类型定义文件?
我在项目中使用uhtml包,它的类型定义文件位于./node_modules/uhtml/types/index.d.ts,但TypeScript编译器(tsc)和语言服务(LSP)都无法识别该文件。目前我通过将./node_modules/uhtml/types复制到本地./types/uhtml/来解决问题,但我希望直接引用node_modules中的类型文件。尝试过多种///<reference指令写法都无效,求指定uhtml使用该特定类型文件的方法。
最小复现示例
package.json
{ "name": "uhtml-path", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "devDependencies": { "uhtml": "^4.2.2" } }
example.js
import { html } from "uhtml";
jsconfig.json
{ "compilerOptions": { "baseUrl": ".", "moduleResolution": "node", "checkJs": true, "target": "ESNext", "module": "ESNext", "strictNullChecks": true, "resolveJsonModule": true, "lib": ["dom", "dom.iterable", "esnext", "WebWorker"] } }
1. 检查并修复uhtml包的类型入口声明
打开./node_modules/uhtml/package.json,查看是否存在"types"或"typings"字段。如果没有,添加以下内容:
"types": "./types/index.d.ts"
这是最根本的解决方式,因为TypeScript默认会读取包package.json里的types字段定位类型定义文件。如果不想修改node_modules内的文件,可以考虑给uhtml包提交PR,或用下面的配置方案绕过。
2. 配置typeRoots指定类型目录
在jsconfig.json的compilerOptions中添加typeRoots,明确告诉TypeScript去uhtml的types目录查找类型:
{ "compilerOptions": { // ...原有配置 "typeRoots": [ "./node_modules/@types", "./node_modules/uhtml/types" ] } }
typeRoots指定了TypeScript扫描类型定义的根目录,默认仅包含./node_modules/@types,添加uhtml的types目录后就能被识别。
3. 使用paths映射关联类型文件
通过paths配置将uhtml的导入直接映射到对应的类型定义文件:
{ "compilerOptions": { // ...原有配置 "paths": { "uhtml": ["./node_modules/uhtml/types/index.d.ts"], "uhtml/*": ["./node_modules/uhtml/types/*"] } } }
这个配置会让TypeScript在解析import { html } from 'uhtml'时,直接关联到指定的类型文件。
4. 手动创建类型声明文件兜底
在项目根目录的./types文件夹下创建uhtml.d.ts,内容如下:
declare module 'uhtml' { export * from '../node_modules/uhtml/types/index.d.ts'; }
同时确保jsconfig.json的include字段包含类型目录:
{ "compilerOptions": { /* ... */ }, "include": [ "./**/*.js", "./types/**/*.d.ts" ] }
这个方案相当于手动给uhtml包创建一个类型入口,指向node_modules里的原始类型文件。
内容的提问来源于stack exchange,提问作者GaryBishop

