执行ESLint命令时无法输出Vue模板内TypeScript类型错误
编辑补充
目前看来该问题暂未找到可行解决方案,经多轮测试验证,eslint + typescript 与 Vue模板之间存在适配链路断层,暂未找到该类问题的合适咨询渠道。
问题现象
搭建集成vue + typescript + prettier + eslint的新项目,所有配置完成后大部分功能正常,仅存在一处异常:
在模板内编写存在类型错误的属性引用(如属性名拼写错误)时,编辑器会给出错误视觉提示,鼠标悬浮显示错误:Property 'myTes' does not exist on type,但执行lint命令eslint --ext .ts,vue --ignore-path .gitignore .时,终端没有任何相关错误输出。
完全相同的拼写错误写在<script>标签内时,可以正常被检测,终端会输出对应错误信息。
复现环境
以下环境组合均测试验证可复现问题:
- Vue CLI 4 + Vetur
- Vue CLI 4 + Volar
- Vite 2 + Vetur
- Vite 2 + Volar
注:模板内错误拼写类实例属性引用时,问题表现完全一致。
问题复现示例
<!-- prettier-ignore --> <template> <div> {{ myTes }} <!-- 执行lint命令时终端无报错 --> </div> </template> <script lang="ts"> import { defineComponent } from 'vue' export default defineComponent({ name: 'App', data() { const myTest = 'testing' console.log(myTes) <!-- 执行lint命令时终端输出报错:'"myTes" is not defined' --> return { myTest, } }, }) </script>
现有配置
.eslintrc.js
module.exports = { root: true, env: { browser: true, es2021: true, node: true, }, extends: [ 'plugin:vue/vue3-essential', 'eslint:recommended', '@vue/typescript/recommended', '@vue/prettier', '@vue/eslint-config-typescript', '@vue/eslint-config-prettier', ], plugins: ['vue'], parser: 'vue-eslint-parser', parserOptions: { parser: { // <script> 标签解析器 js: 'espree', // <script lang="ts"> 标签解析器 ts: '@typescript-eslint/parser', // Vue指令、模板插值解析器,未指定时跟随<script lang>配置 '<template>': 'espree', }, ecmaVersion: 'latest', sourceType: 'module', ecmaFeatures: { jsx: true, }, }, rules: [ ... 自定义规则] }
tsconfig.json
{ "compilerOptions": { "target": "esnext", "useDefineForClassFields": true, "module": "esnext", "moduleResolution": "node", "strict": true, "jsx": "preserve", "sourceMap": true, "resolveJsonModule": true, "isolatedModules": true, "esModuleInterop": true, "lib": ["esnext", "dom"], "skipLibCheck": true, "baseUrl": ".", "paths": { "@/*": [ "src/*" ] } }, "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"], "references": [{ "path": "./tsconfig.node.json" }] }
根因分析
问题出在ESLint解析器配置错误:
- 编辑器侧的类型错误提示来自Volar/Vetur直接调用TypeScript语言服务做的静态校验,链路不经过ESLint,所以能正常识别模板内的类型错误。
- 命令行执行ESLint校验时,
<script lang="ts">块使用配置的@typescript-eslint/parser做解析,该解析器支持TS类型检查,因此脚本书写的拼写错误可以被正常捕获。 - 模板部分被手动指定使用
espree作为解析器,这是原生JavaScript解析器,不具备TypeScript类型校验能力,仅能做基础JS语法检查,无法识别属性不存在这类TS类型错误,因此终端无对应报错输出。
解决方案
修改.eslintrc.js中parserOptions.parser的模板解析器配置,将<template>对应的解析器从espree替换为@typescript-eslint/parser,修改后的配置片段如下:
parserOptions: { parser: { js: 'espree', ts: '@typescript-eslint/parser', '<template>': '@typescript-eslint/parser', // 其余parserOptions配置保持不变 }, }
修改完成后重新执行lint命令,即可正常检测到Vue模板内的TypeScript类型错误。
内容的提问来源于stack exchange,提问作者Rudi Ørnhøj
相关产品推荐
相关产品推荐

