正确处理未定义的声明文件(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(没有 @type/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选项指定可能包含类型信息的 packages 。该文档一直在说编译器正在寻找软件包

我已经复制了您描述的结构,并获得了与您相同的错误。然后,我在typings下创建了一个react-native-camera并将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目录。

flowtype文档,图书馆定义部分,它说:

libdef是一个特殊文件,可告知流量有关类型签名的流程 您的一些特定的第三方模块或您的模块包 应用程序用途。如果您熟悉具有标题的语言 文件(例如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 修改所需的。

最新更新