我试图从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


当前回答

尝试添加到tsconfig。"noImplicitAny": false 为我工作

其他回答

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本地服务器,并在执行以下操作后重新启动它:

1-创建。d。Ts文件手动,你只需要做以下工作:

2 -进入SRC文件夹

3 -创建global.d.ts文件

4 -像这样声明模块:

declare module 'module-name';

我之前在这里回答过,很不错

对于那些想知道我是如何克服这些的人。我做了一些hack的东西。

在我的项目中,我创建了一个名为@types的文件夹,并将其添加到tsconfig中。Json来找到所有需要的类型。所以它看起来像这样

"typeRoots": [
  "../node_modules/@types",
  "../@types"
]

在里面我创建了一个名为alltypes。d。ts的文件。从中找出未知类型。所以对我来说,这些是未知的类型,我把它加在那里。

declare module 'react-materialize';
declare module 'react-router';
declare module 'flux';

现在typescript不再抱怨找不到类型了。现在是双赢的局面:)

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

e.g.

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

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

只要为react安装必要的类型,它就应该解决这个错误。

如果你用的是纱线:

yarn add @types/react @types/react-dom @types/react-router-dom -D

如果你正在使用npm:

npm install @types/react @types/react-dom @types/react-router-dom --save-dev