ESLint插件配置后为什么还是报“Unexpected token”错误?
在项目里装了eslint-plugin-react和@typescript-eslint/eslint-plugin,配置了相关规则,但写React组件时还是报“Unexpected token”错误。代码明明能正常运行啊。
比如这个组件:
class MyComponent extends React.Component {
render() {
return <div>{this.props.message}</div>;
}
}
已经检查过.eslintrc配置了”plugins”: [“react”, “@typescript-eslint”],parser也用了@typescript-eslint/parser。尝试过删除node_modules重装,但问题依旧。是不是插件版本冲突了?
.eslintrc文件里的parser和parserOptions部分,确保它长这样:{
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2020,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"plugins": ["react", "@typescript-eslint"]
}
另外检查一下你的ESLint版本和插件版本是否兼容。比如
eslint-plugin-react和@typescript-eslint/eslint-plugin的版本最好升级到最新稳定版。如果还不行,可以试试加上extends配置:{
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"plugin:@typescript-eslint/recommended"
]
}
然后再运行一下看看问题还在不在。如果还报错的话,可以发一下完整的
.eslintrc配置,我再帮你看看。extends或者parserOptions没配好。贴一个我正在用的配置,复制过去试试:重点看
parserOptions.ecmaFeatures.jsx这个选项,不打开 ESLint 没法识别 JSX 语法。另外确保
@typescript-eslint/eslint-plugin和@typescript-eslint/parser的版本一致,如果用了eslint-plugin-react最好也装对应的@typescript-eslint/eslint-plugin-tslint。实在不行可以加个
.eslintignore把报错文件暂时排除,再一点点排查。