React TypeScript项目ESLint报Parsing error: Unexpected token !的解决方法
解决"Parsing error: Unexpected token !"错误
问题根源
你代码里的!是TypeScript的非空断言操作符,但当前ESLint配置使用的babel-eslint解析器不支持TypeScript语法,这直接导致了解析错误。
修复步骤
替换解析器依赖
先卸载无用的babel-eslint:npm uninstall babel-eslint安装TypeScript专属的ESLint解析器:
npm install @typescript-eslint/parser --save-dev更新eslintrc.js配置
将解析器替换为@typescript-eslint/parser,并完善TypeScript文件的规则配置:module.exports = { env: { browser: true, es2021: true }, extends: [ 'plugin:react/recommended', 'plugin:@typescript-eslint/recommended', // 启用TypeScript推荐规则 'prettier' ], overrides: [ { files: ['*.ts', '*.tsx'], parser: '@typescript-eslint/parser', // 为TS文件指定正确解析器 parserOptions: { project: ['./tsconfig.json'] }, plugins: ['@typescript-eslint'] } ], parserOptions: { ecmaFeatures: { jsx: true }, ecmaVersion: 'latest', sourceType: 'module' }, plugins: ['react', '@typescript-eslint', 'prettier', 'simple-import-sort'], };校验tsconfig.json配置
确保你的tsconfig.json包含基础TypeScript配置,示例如下:{ "compilerOptions": { "target": "ES2020", "module": "ESNext", "jsx": "react-jsx", "strict": true, "moduleResolution": "node", "esModuleInterop": true }, "include": ["src/**/*"] }重启ESLint服务
修改配置后,重启编辑器或ESLint服务,让新配置生效。
补充说明
@typescript-eslint/parser是专为TypeScript打造的ESLint解析器,能完整识别TypeScript的所有语法特性(包括非空断言、可选链等)。- 加入
plugin:@typescript-eslint/recommended可启用TypeScript相关的ESLint规则,进一步规范代码质量。
内容的提问来源于stack exchange,提问作者DamnGood
相关产品推荐
相关产品推荐

