我使用的JS库没有为TypeScript提供@type定义,所以我创建了自己的.d.ts
文件。让我们称之为foo.d.ts
。我的项目结构如下:
...
.next/
pages/
...
typings/
foo.d.ts
...
tsconfig.json
我的VS代码对这个定义没有问题,我可以在我的组件中导入,比如:
import {Foo} from "foo";
但在运行时,我在浏览器控制台中收到了这个错误
找不到模块:无法解析"foo">
我已尝试添加
"typeRoots":["node_modules/@types";,"打字员";]
到我的tsconfig.json
,但没有帮助。我还尝试将foo.d.ts
显式添加到添加next-env.d.ts
的include部分。
foo.d.ts
看起来像这样:
declare module 'foo' {
declare interface ValidationError {
message?: string;
}
declare namespace Foo {
class Bar {
constructor(config: any, displayErrorsCallback: (data: ValidationError[]) => void, onSubmitTriggered: () => void);
}
}
}
更新(添加tsconfig(
{
"compilerOptions": {
"target": "es6",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"typeRoots": [
"node_modules/@types",
"typings"
]
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules"
]
}
只需在文件名后添加.d
,即可将类型定义导入为import {Foo} from "foo.d";
无论何时导入*.d.ts
,都可以像那样导入它们,无需编辑配置。