typescript - 创建 React App 找不到声明的模块

标签 typescript create-react-app typescript-typings tsconfig react-tsx

我有一个使用 CRA typescript 创建的项目。

在项目的根目录下存在 tsconfig.json 和一个名为 types 的文件夹。在 types 文件夹中,我为一个模块创建了一个 modulename.d.ts 文件,该文件在 node_modules 中没有默认类型,而且在 @types\module-name< 中也没有任何内容.

但是我在编译时得到了错误。

Type error: Could not find a declaration file for module 'thename'. '/*/node_modules/thename/dist/entry.js' implicitly has an 'any' type.

为什么编译器在类型文件夹中找不到类型声明?

// .d.ts
declare module 'foo-react' {
    import * as React from 'react';
    // ...
}

这是 tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": { "*": ["types/*"] },
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "plugins": [{ "name": "typescript-tslint-plugin" }],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve"
  },
  "include": ["src"]
}

最佳答案

原来是这样

  1. 我将自定义类型文件夹重命名为 @types
  2. @types 的路径文件夹(我在项目根目录下自定义的文件夹)应添加到 types属性而不是 paths属性。 "types":["./@types"]
  3. @types结构类似于 @types/<module_name>/index.d.ts 的文件夹或 @types/moduleName.d.ts .现在文件可以将该模块声明为 any或详细声明所有类型。

类型编译器选项的定义 Typescript handbook

--types string[] List of names of type definitions to include. See @types, —typeRoots and —types for more details.

关于typescript - 创建 React App 找不到声明的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55230403/

相关文章:

javascript - 在 TypeScript 中使用外部 javascript 脚本

javascript - 子组件之间的通信 - 触发和更改

typescript :声明类实现接口(interface)

TypeScript:默认值不是构造函数

ruby-on-rails - 在 Heroku 上使用 Rails API 部署 Create-React-App

visual-studio - angular 2 - PrimeNg teamcity/visual Studio 编译失败(不包括 node_modules)

javascript - 如何在 Mantine 中设置标题组件的样式?

angular - ionic2 将 ngx-translate 应用于菜单项

proxy - 是否可以从 create-react-app 代理 html get 请求到/graphql?

node.js - React 创建应用程序热重载并不总是在 linux 上工作