You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 08:39:29