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

时间:2017-11-30 12:20:13

标签: reactjs typescript react-native node-modules typescript-typings

我收到了以下错误

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"]
}

2 个答案:

答案 0 :(得分:6)

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

我已经复制了你描述的结构并且遇到了同样的错误。然后我在react-native-camera下创建了typings并移动了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目录。

答案 1 :(得分:0)

来自flowtype document的图书馆定义部分,它说:

  

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 修改。