使用以下代码创建了一个 javascript 文件:
import React, {Component, Fragment} from "react"
import PropTypes from "prop-types"
export default class DefaultBootstrap extends Component {
render() { return (<div>Hi</div>) }
}
DefaultBootstrap.propTypes = {
name: PropTypes.bool.isRequired
}
当我运行 npm start
时,它显示以下 linter 错误:
xxx/xxx/index.js
1:1 warning Definition for rule 'prop-types' was not found prop-types
所以我的问题是,为什么即使我已经在上面定义了 prop-types 规则,它仍然向我显示上述警告?
我使用 Webpack、Babel、React 和 Eslinter 来设置我的应用程序。
.eslintrc.json
{
"parser": "babel-eslint",
"plugins": ["react"],
"rules": {
"prop-types": ["warn"],
}
}
package.json (Click To See Complete File)
{
"devDependencies": {
"@babel/core": "7.1.2",
"babel-eslint": "10.0.1",
"babel-loader": "8.0.4",
"eslint": "5.6.1",
"eslint-loader": "2.1.1",
"eslint-plugin-react": "7.11.1",
"webpack": "4.20.2",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5"
},
"dependencies": {
"node": "^10.11.0",
"prop-types": "15.6.2",
"react": "16.5.2",
"react-dom": "16.5.2",
"react-scripts": "2.0.3",
}
}
webpack.config.js (Click here To See Complete File)
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
},
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader']
},
最佳答案
在查看您的代码之前,ESLint 首先寻找 prop-types
规则的实现。错误消息说它找不到该规则。由于 prop-types
规则是由插件 eslint-plugin-react
提供的,并且不是内置规则之一,因此您需要在其前面加上前缀在你的 .eslintrc.json
中使用插件名称和斜杠命名:react/prop-types
。这告诉 ESLint 它应该在 eslint-plugin-react
中寻找 prop-types
规则。
{
"parser": "babel-eslint",
"plugins": ["react"],
"rules": {
"react/prop-types": ["warn"],
}
}
您可以在 rule configuration docs 中阅读更多内容.
关于javascript - Eslint 未检测到 React 组件的定义属性类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52699469/