【问题标题】:Create React App cannot find declared module创建 React App 找不到声明的模块
【发布时间】:2019-08-09 08:31:03
【问题描述】:

我有一个使用 CRA 打字稿创建的项目。

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

但我在编译时收到错误。

类型错误:找不到模块“名称”的声明文件。 '/*/node_modules/thename/dist/entry.js' 隐含了一个 'any' 类型。

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

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

【问题讨论】:

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


    【解决方案1】:

    原来如此

    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[] 要包含的类型定义的名称列表。详情请见@types, —typeRoots and —types

    【讨论】:

      猜你喜欢
      • 2019-12-29
      • 2022-07-12
      • 2019-03-16
      • 2019-07-26
      • 2021-02-21
      • 2017-05-29
      • 1970-01-01
      • 2022-06-12
      • 2022-11-06
      相关资源
      最近更新 更多