我正在尝试从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一起使用。
反应物质化的index.js
看起来像这样。但是如何在我自己的文件中为模块导入解决这个问题..
https://github.com/react-materialize/react-materialize/blob/master/src/index.js
对于那些想知道我是如何克服这一点的人。我做了一些黑客的东西。
在我的项目中,我创建了一个名为@Types
的文件夹,并将其添加到tsconfig.json中,以便从中查找所有必需的类型。所以看起来有点像这样 -
"typeRoots": [
"../node_modules/@types",
"../@types"
]
在里面我创建了一个名为alltypes.d.ts
的文件。从中查找未知类型。所以对我来说这些都是未知的类型,我在那里添加了它。
declare module 'react-materialize';
declare module 'react-router';
declare module 'flux';
所以现在打字稿并没有抱怨找不到的类型。 :)现在胜利局面:)
如果您使用的模块没有@types/<package>
,您可以通过添加// @ts-ignore
轻松解决问题,即
// @ts-ignore
import { render } from 'react-snapshot';
或者,您可以创建以下缺少的@types/<package>
:
在tsconfig.json中,设置"noImplicitAny": false
为我修复了这个问题
我有类似的错误,但对我来说这是react-router
。通过安装类型来解决它。
npm install --save @types/react-router
错误:
(6,30): error TS7016: Could not find a declaration file for module 'react-router'. '\node_modules\react-router\index.js' implicitly has an 'any' type.
如果你想在网站上禁用它,你可以改为编辑tsconfig.json
并将noImplicitAny
设置为false
。
我对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"]
}
您需要做的就是运行以下脚本。然后,删除/重新安装要使用的模块。
npm install --save @types/react-redux
此外,如果您尝试使用的软件包具有自己的类型文件,并且它在package.json typings
属性中列出,则此错误会得到修复
像这样:
{
"name": "some-package",
"version": "X.Y.Z",
"description": "Yada yada yada",
"main": "./index.js",
"typings": "./index.d.ts",
"repository": "https://github.com/yadayada.git",
"author": "John Doe",
"license": "MIT",
"private": true
}
更hacky的方法是在boot.tsx中添加例如
import './path/declare_modules.d.ts';
同
declare module 'react-materialize';
declare module 'react-router';
declare module 'flux';
在declare_modules.d.ts
它有效,但其他解决方案是更好的IMO。
我所做的是在项目文件夹目录中从nodejs命令提示符运行以下命令:
npm init
npm install -g webpack
npm install --save react react-dom @types/react @types/react-dom
npm install --save-dev typescript awesome-typescript-loader source-map-loader
npm install ajv@^6.0.0
npm i react-html-id
import UniqueId from 'react-html-id';
导入App.js文件中的包(在节点模块中)我做了以上(虽然我已经安装了npm)并且它工作了!
工作得很好
npm install @types/react-materialize
对于我的情况,问题是类型没有被添加到devDependencies下的package.json文件来修复它我运行npm install --save-dev @types/react-redux
注意--save-dev