ESLint 9 搭配 Vue3+TypeScript 出现解析错误及解决过程
ESLint 9 搭配 Vue3+TypeScript 出现解析错误及解决过程
最近在做 Vue3 + TypeScript 项目时,想集成 ESLint 代码检查流水线,结果踩了好几个坑,跟大家分享下问题和解决办法。
遇到的问题
我用的是 ESLint 9.34.0,把 ESLint 配置文件放在了 /config/eslint.config.cjs,还在 package.json 里用 --config config/eslint.config.cjs 指定了路径。结果运行 npm run lint 时直接报错:
error Parsing error: Unexpected token <
一开始我以为是缺解析器,就试着在 languageOptions 里加了 "parser": "@babel/eslint-parser",结果又报新错误:
TypeError: Key "languageOptions": Key "parser": Expected object with parse() or parseForESLint() method.
当时的错误配置文件是这样的:
module.exports = [ { languageOptions: { globals: { window: 'readonly', document: 'readonly', console: 'readonly', }, parserOptions: { ecmaVersion: 2021, sourceType: 'module', }, }, rules: { 'no-unused-vars': 'warn', 'no-console': 'warn', }, ignores: ['dist/', 'node_modules/'], }, ];
解决过程
后来仔细排查后终于搞定了!问题出在这几个地方:配置文件的扩展名和格式不对,而且漏掉了 Vue 专用的 ESLint 插件。
我把配置文件改成了 eslint.config.js(用 ES 模块格式而非 CommonJS),同时补全了必要的插件和规则,现在配置文件能正常工作了:
import eslint from '@eslint/js' import pluginVue from 'eslint-plugin-vue' import globals from 'globals' import tseslint from 'typescript-eslint' export default tseslint.config( { ignores: ['dist/', 'node_modules/'], }, { files: ['**/*.{ts,vue}'], extends: [ eslint.configs.recommended, ...tseslint.configs.recommended, ...pluginVue.configs['flat/recommended'], ], languageOptions: { ecmaVersion: 'latest', sourceType: 'module', globals: { ...globals.browser, }, parserOptions: { parser: tseslint.parser, }, }, rules: { 'no-unused-vars': 'warn', 'no-console': 'warn', }, } )
关键踩坑点总结
- ESLint 9 采用扁平配置(flat config),推荐用 ES 模块的
.js文件而非 CommonJS 的.cjs格式 - 必须引入
eslint-plugin-vue插件,否则 ESLint 无法识别.vue文件里的模板标签,就会出现<解析错误 - 结合
typescript-eslint插件处理 TypeScript 代码,同时继承它和 Vue 插件的推荐规则,才能覆盖 TS 和 Vue 文件的检查需求 - 要明确指定检查的文件类型包含
.ts和.vue,避免漏检
内容来源于stack exchange
相关产品推荐
相关产品推荐

