混合JS与TS项目中ESLint不再对JS/JSX文件报错的解决方法
问题描述
当前我的ESLint配置(如下)可以正常检查.ts和.tsx文件并抛出错误,但.js和.jsx文件完全没有ESLint提示,请问如何修改配置让两类文件都能被正确检查?
原配置:
module.exports = { root: true, parser: "@babel/eslint-parser", parserOptions: { requireConfigFile: false, babelOptions: { presets: ["@babel/preset-react"], }, }, plugins: ["react", "react-hooks"], rules: { "no-console": "off", "react-hooks/exhaustive-deps": "off", "no-unused-vars": "off", "@typescript-eslint/no-unused-vars": "off", "@no-restricted-globals": "off", }, overrides: [ { files: ["**/*.ts", "**/*.tsx"], env: { browser: true, es6: true, node: true }, extends: [ "eslint:recommended", "plugin:@typescript-eslint/eslint-recommended", "plugin:@typescript-eslint/recommended", ], parser: "@typescript-eslint/parser", parserOptions: { ecmaFeatures: { jsx: true }, ecmaVersion: 2018, sourceType: "module", project: "./tsconfig.json", }, plugins: ["@typescript-eslint"], rules: { "no-console": "off", "react-hooks/exhaustive-deps": "off", "no-unused-vars": "warn", "@typescript-eslint/no-unused-vars": "warn", "@no-restricted-globals": "off", "@typescript-eslint/no-explicit-any": "off", "@typescript-eslint/ban-ts-comment": "off", }, }, ], };
解决方案
问题出在全局规则里直接关闭了核心检查项,同时没给.js/.jsx文件配置必要的推荐规则集。我们可以通过overrides分别给两类文件配置独立的检查规则,确保各自生效:
修改后的配置:
module.exports = { root: true, // 全局通用配置,所有文件都会继承(后续overrides会覆盖对应文件的专属配置) parser: "@babel/eslint-parser", parserOptions: { requireConfigFile: false, babelOptions: { presets: ["@babel/preset-react"], }, ecmaFeatures: { jsx: true }, ecmaVersion: 2018, sourceType: "module" }, plugins: ["react", "react-hooks"], env: { browser: true, es6: true, node: true }, rules: { "no-console": "off", "react-hooks/exhaustive-deps": "off", "@no-restricted-globals": "off" }, overrides: [ // 专门配置.js/.jsx文件的检查规则 { files: ["**/*.js", "**/*.jsx"], extends: ["eslint:recommended", "plugin:react/recommended"], rules: { "no-unused-vars": "warn", // 可根据需求添加更多JS专属规则 } }, // 保留并优化.ts/.tsx文件的检查规则 { files: ["**/*.ts", "**/*.tsx"], extends: [ "eslint:recommended", "plugin:@typescript-eslint/eslint-recommended", "plugin:@typescript-eslint/recommended", "plugin:react/recommended" ], parser: "@typescript-eslint/parser", parserOptions: { project: "./tsconfig.json" }, plugins: ["@typescript-eslint"], rules: { "no-unused-vars": "warn", "@typescript-eslint/no-unused-vars": "warn", "@typescript-eslint/no-explicit-any": "off", "@typescript-eslint/ban-ts-comment": "off" } } ] };
关键修改点:
- 全局配置精简:把通用的
env、parserOptions提到全局,避免重复配置;移除全局规则里关闭no-unused-vars的设置,让不同文件类型在各自的overrides里单独配置。 - 新增JS文件规则块:在
overrides里添加.js/.jsx的配置,引入eslint:recommended和plugin:react/recommended基础规则集,开启no-unused-vars的警告提示。 - TS配置补全:给TS文件加上
plugin:react/recommended,确保React相关规则生效;保留原有的TypeScript专属规则和配置。
修改后,.js/.jsx会用Babel解析器和ESLint推荐规则做检查,.ts/.tsx用TypeScript解析器和TS专属规则,两类文件都能正常触发ESLint的错误提示。
内容的提问来源于stack exchange,提问作者Owenn
相关产品推荐
相关产品推荐

