浏览器端Vite TypeScript项目中无法使用jsts类型定义
浏览器端Vite TypeScript项目中jsts类型导入报错问题
已安装依赖:
$ npm ls --depth=0 | grep jsts ├── @types/jsts@0.17.21 ├── jsts@2.8.1
尝试导入代码:
import Centroid from 'jsts/org/locationtech/jts/algorithm/Centroid'; import * as jsts from 'jsts/org/locationtech/jts';
触发TypeScript错误:
ERROR(TypeScript) Could not find a declaration file for module 'jsts/org/locationtech/jts/algorithm/Centroid'. '/home/[ommited...]/node_modules/jsts/org/locationtech/jts/algorithm/Centroid.js' implicitly has an 'any' type. Try `npm i --save-dev @types/jsts` if it exists or add a new declaration (.d.ts) file containing `declare module 'jsts/org/locationtech/jts/algorithm/Centroid';` ERROR(TypeScript) Could not find a declaration file for module 'jsts/org/locationtech/jts'. '/home/[ommited...]/node_modules/jsts/org/locationtech/jts/index.js' implicitly has an 'any' type. Try `npm i --save-dev @types/jsts` if it exists or add a new declaration (.d.ts) file containing `declare module 'jsts/org/locationtech/jts';
项目tsconfig.json配置:
{ "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "lib": ["ES2020", "DOM", "DOM.Iterable"], "module": "ESNext", /* Bundler mode */ "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", /* Linting */ "strict": true, "strictNullChecks": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "paths": { "react": [ "./node_modules/@types/react" ] } }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] }
问题原因
@types/jsts@0.17.21是针对jsts 0.17.x版本的类型定义,而你安装的jsts是2.8.1,版本差异导致类型定义的模块路径和实际jsts包的结构不匹配,TypeScript无法找到对应路径的类型声明。
解决方法
方法1:调整导入方式(优先推荐)
jsts 2.x版本通常支持从根模块直接导出核心类,无需使用深层路径导入,修改导入代码为:import { Centroid } from 'jsts';方法2:补充自定义类型声明
如果必须使用深层路径导入,可在项目中创建自定义类型声明文件:- 在
src目录下新建types/jsts.d.ts文件 - 添加以下内容:
declare module 'jsts/org/locationtech/jts/algorithm/Centroid' { export default class Centroid { // 根据实际使用需求补充类的方法和属性,暂时可先用any类型占位 compute(geometry: any): any; } } declare module 'jsts/org/locationtech/jts' { export const Centroid: typeof import('jsts/org/locationtech/jts/algorithm/Centroid').default; // 如需其他模块,可继续补充对应的declare module }- 确保tsconfig.json的
include字段包含src/types(当前配置的include: ["src"]已经覆盖,无需额外修改)
- 在
方法3:尝试匹配版本的类型包
检查npm是否有适配jsts 2.x的类型包,若存在,卸载旧的@types/jsts并安装对应版本:npm uninstall @types/jsts npm install -D @types/jsts@适配2.8.1的版本号(注:目前@types/jsts最高版本为0.17.x,暂无官方适配2.x的类型包,此方法可能不可行)
内容的提问来源于stack exchange,提问作者Marcus Junius Brutus
相关产品推荐
相关产品推荐

