Node.js 20下配置ESLint+Prettier+TypeScript及.ts文件无ESLint报错解决
解决TS文件无ESLint报错的问题
1. 安装TypeScript相关ESLint依赖
ESLint默认不支持TypeScript语法校验,必须安装专属解析器和插件:
npm install -D @typescript-eslint/eslint-plugin @typescript-eslint/parser typescript
2. 更新eslint.config.mjs配置
修改ESLint配置文件,添加TS解析器、插件并指定校验范围:
import js from '@eslint/js'; import tseslint from '@typescript-eslint/eslint-plugin'; import tsParser from '@typescript-eslint/parser'; export default [ // 基础JS规则 js.configs.recommended, // TS专属规则配置 { files: ['**/*.ts', '**/*.tsx'], // 匹配所有TS/TSX文件 languageOptions: { parser: tsParser, parserOptions: { ecmaVersion: 'latest', sourceType: 'module', project: './tsconfig.json' // 关联tsconfig,可选但推荐用于类型校验 } }, plugins: { '@typescript-eslint': tseslint }, rules: { ...tseslint.configs.recommended.rules, // 可添加自定义TS规则 } }, // 原有JS文件配置 { files: ['**/*.js'], rules: { // 你的JS规则 } } ];
3. 检查VS Code的settings.json配置
确保ESLint启用TS文件校验,添加或修改以下配置:
{ "editor.codeActionsOnSave": { "source.fixAll.eslint": true }, "eslint.validate": [ "javascript", "typescript" // 必须添加此行,让ESLint处理TS文件 ], "eslint.enable": true }
4. 验证配置并重启服务
- 确保项目根目录存在
tsconfig.json(若启用了parserOptions.project),基础配置示例:
{ "compilerOptions": { "target": "ESNext", "module": "ESNext", "strict": true }, "include": ["src/**/*"] }
- 重启VS Code,或按
Ctrl+Shift+P(Windows)/Cmd+Shift+P(Mac)执行「ESLint: Restart ESLint Server」命令,使配置生效。
5. 完善Prettier与ESLint联动(可选)
若需二者协同工作,安装依赖并更新ESLint配置:
npm install -D eslint-config-prettier eslint-plugin-prettier
在eslint.config.mjs中添加:
import prettier from 'eslint-plugin-prettier'; import prettierConfig from 'eslint-config-prettier'; export default [ // ...其他配置 prettierConfig, // 禁用与Prettier冲突的ESLint规则 { plugins: { prettier }, rules: { 'prettier/prettier': 'error' // 将Prettier格式问题标记为ESLint错误 } } ];
内容的提问来源于stack exchange,提问作者Abner Matheus
相关产品推荐
相关产品推荐

