繁体   English   中英

处理未定义的声明文件(index.d.ts)的正确方法

[英]Correct way to handle undefined declaration files (index.d.ts)

我收到以下错误

error TS7016: Could not find a declaration file for module 'react-native-camera'. '/Users/ilja/Documents/Repositories/blok/node_modules/react-native-camera/index.js' implicitly has an 'any' type.
  Try `npm install @types/react-native-camera` if it exists or add a new declaration (.d.ts) file containing `declare module 'react-native-camera';`

作为快速解决方案,我在项目的根目录下创建了typings/index.d.ts (没有@ types / react-native-camera)文件,并在其中填充了

declare module 'react-native-camera';

然后,在我的tsconfig文件中,将其添加到这样的类型根目录中

"typeRoots": ["node_modules/@types", "./typings"],

但是在构建时仍然出现相同的错误,导致我认为自己的实现不正确,我错过了什么?

编辑,我完整的tsconfig看起来像这样

{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "lib": ["es7"],
    "allowJs": true,
    "checkJs": true,
    "jsx": "react-native",
    "removeComments": true,
    "outDir": "./dist",
    "typeRoots": ["node_modules/@types", "./typings"],
    "experimentalDecorators": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "allowSyntheticDefaultImports": true,
    "strict": true
  },
  "exclude": ["./node_modules", "./android", "./ios", "./assets", "./__tests__", "./dist"],
  "include": ["./src"]
}

typeRoots选项指定在哪里查找可能包含类型信息的软件包 文档一直说编译器正在寻找软件包

我已经复制了您描述的结构,并得到了与您相同的错误。 然后创建了一个react-native-cameratypings和移动index.d.ts那里,以便我结束了这样的结构:

typings/
└── react-native-camera
    └── index.d.ts

使用这种结构,编译就可以正常进行。

使用typings目录结构是好的,如果你想的那种结构。 对于某些项目,我使用typings目录。 对于其他项目,我希望使用更简单的方法:源树中的.d.ts文件声明了需要声明的所有内容。 因此,如果我从您提供的描述开始,但转储typings ,而是添加包含以下内容的src/definitions.d.ts

declare module 'react-native-camera';

然后代码编译就可以了。

使用哪种确实是一个偏好问题。 通常,当一个项目变得如此复杂,以至于src/definitions.d.ts最终被难以管理或很难理解,我移动到使用typings目录。

在库定义部分的流程类型文档中,它说:

libdef是一个特殊文件,用于通知Flow您的应用程序使用的某些特定第三方模块或模块包的类型签名。 如果您熟悉具有头文件的语言(例如C ++),则可以将libdefs视为一个类似的概念。

一般最佳做法

尝试为您的项目使用的每个第三方库提供一个libdef。

在根路径中查看.flowconfig ,您将看到它已经在此处定义。

[libs]
node_modules/react-native/Libraries/react-native/react-native-interface.js
node_modules/react-native/flow
./libdefs.js

然后在根路径中查找libdefs.js ,它应该在那里。 或者只是自己创建。

对于每个模块,请按以下说明进行声明。 rxjs为例:

declare module 'rxjs' { declare var exports: any; }

这是官方建议的方式,无需index.d.ts修改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM