简体   繁体   English

React找不到TypeScript声明模块

[英]React can't find TypeScript declarations module

I'm trying to use the react-csv-reader package in a React project that was created with create-react-app --typescript . 我正在尝试在使用create-react-app --typescript的React项目中使用react-csv-reader包。 Since react-csv-reader doesn't come with a types declaration file, I created one myself. 由于react-csv-reader不附带类型声明文件,因此我自己创建了一个。 I created a file types/react-csv-reader/index.d.ts . 我创建了一个文件types/react-csv-reader/index.d.ts VS Code's Intellisense can find it just fine (I can command-click on the function name in module where I'm using react-csv-reader, and it takes me to my declarations file. It also complains when I don't have all the required props, etc.). VS Code的Intellisense可以很好地找到它 (我可以在我使用react-csv-reader的模块中命令单击该函数的名称,并将其带到声明文件。当我没有所有文件时,也会抱怨所需的道具等)。

But when I run npm start , I get this: 但是当我运行npm start ,我得到了:

Failed to compile.

./src/screens/ReadCsv.tsx
Module not found: Can't resolve '../types/react-csv-reader' in '/my/proj/root/src/screens'

Here's my index.d.ts : 这是我的index.d.ts

import React from 'react'

interface CSVReaderProps {
  cssClass?: string
  cssInputClass?: string
  label?: string
  onFileLoaded: (data: any, filename: string) => void
  onError: () => void
  inputId?: string
  inputStyle?: any
  parserOptions?: any
}

declare const CSVReader: React.SFC<CSVReaderProps>

export default CSVReader

Because typescript don't know where are your definition files, so you have to tell him in your tsonfig.json. 因为打字稿不知道您的定义文件在哪里,所以您必须在tsonfig.json中告诉他。

{ 
  "compilerOptions": {
    "typeRoots" : [
      "node_modules/@types",
      "./your/types/folder"
    ] 
  } 
}

Note that I added node_modules , otherwise its types are not included. 请注意,我添加了node_modules ,否则不包括其类型。

https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types

The right combination of things to make this work was: 使这项工作正确的组合是:

  1. Put everything in index.d.ts inside a declare module 'react-csv-reader' {} block 将所有内容放入declare module 'react-csv-reader' {}块内的index.d.ts中
  2. import it as import CSVReader from 'react-csv-reader' instead of what I was doing, which was import CSVReader from '../types/react-csv-reader' . import CSVReader from 'react-csv-reader'导入它作为import CSVReader from 'react-csv-reader'而不是import CSVReader from '../types/react-csv-reader'

I did not have to change anything in tsconfig.json. 我不必更改tsconfig.json中的任何内容。 I still don't understand why it worked before as far as VS Code Intellisense was concerned, but this way works with that and is compiled happily by React. 我仍然不明白为什么就VS Code Intellisense而言,它为什么能起作用,但是这种方式可以解决这个问题,并且可以被React高兴地编译。

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

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