我试图从react-materialize导入组件

import {Navbar, NavItem} from 'react-materialize';

但是当webpack编译我的.tsx时,它会为上面的-抛出一个错误

ERROR in ./src/common/navbar.tsx
(3,31): error TS7016: Could not find a declaration file for module 'react-materi
alize'. 'D:\Private\Works\Typescript\QuickReact\node_modules\react-materialize\l
ib\index.js' implicitly has an 'any' type.

有什么解决办法吗?我不确定如何解析此导入语句以使用ts-loader和webpack。

react-materialize的index.js是这样的。但是我如何解决这个模块导入在我自己的文件?

https://github.com/react-materialize/react-materialize/blob/master/src/index.js


当前回答

可能在某些情况下,某些依赖项没有类型,ts会强制您为此包含类型。有一种变通方法可以解决这个问题,那就是使用javascript。

e.g.

import {Charts} from "react-charts";//error:无法找到模块'react-charts'的声明文件。

const ReactChart = require("react-charts");/ /没有错误

其他回答

react-router-dom有同样的错误。

此错误发生在您正在处理typescript项目时,默认模块没有提供typescript所需的类型。

所以我在npmjs.com上搜索了一个名为@types/react-router-dom的包,如果它不是你正在寻找的react-router-dom,然后用你的untyped模块替换react-router-dom。

在npm网站上寻找最后一个版本,然后将它添加到你的包中。Json是这样的:

[...]
"dependencies": {
    [...]
    "@types/react-router-dom": "^5.1.8",
    [...]
  },
[...]

一旦完成,运行yarn install

那么它应该会摇滚起来!

我在使用react-redux类型时也遇到了同样的问题。最简单的解决方案 被添加到tsconfig.json:

"noImplicitAny": false

例子:

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "jsx": "react",
    "lib": ["es6"],
    "moduleResolution": "node",
    "noEmit": true,
    "strict": true,
    "target": "esnext",
    "noImplicitAny": false,
  },
  "exclude": ["node_modules", "babel.config.js", "metro.config.js", "jest.config.js"]
}

无法找到模块“react/jsx-runtime”的声明文件

如果有人有这个错误,那么你会惊讶地发现,当使用create-react-app创建react应用程序时,它只在package.json中显示@types/react。但是如果你检查node_modules/@types文件夹,你将找不到任何react文件夹。

解决方案是完全清除node_modules文件夹并重新安装- npm install,或者可能可以使用单个模块安装- npm install @types/react。

当我使用typescript添加react-router-dom到新的CRA应用程序时,我有这个问题。在我添加@types/react-router后,这个问题得到了修复。

如果你在使用npm react时遇到问题,请安装——save @types/reactnpm install——save @types/react