精准配置ESLint,仅检查vue组件中的typescript代码
在逐步将老项目迁移到TypeScript的过程中,如何配置ESLint只检查.vue文件中使用TypeScript ( lang=”ts” ) 的部分,而忽略JavaScript代码,是一个常见的难题。本文提供一种有效的ESLint配置方案,避免overrides配置的常见误区。
首先,在.eslintrc.JS文件中进行如下配置:
module.exports = { // ...其他配置... overrides: [ { files: ['*.vue'], parser: 'vue-eslint-parser', parserOptions: { parser: '@typescript-eslint/parser', }, rules: { // TypeScript相关的ESLint规则 }, }, { files: ['*.vue'], //关键:排除所有.vue文件,避免重复检查 excludedFiles: ['**/*.vue'], parser: 'vue-eslint-parser', parserOptions: { parser: 'espree', ecmaVersion: 2020, sourceType: 'module', }, rules: { // JavaScript相关的ESLint规则 (不会应用于TypeScript代码) }, }, ], };
此配置利用overrides定义两套规则:第一套针对.vue文件中的TypeScript代码;第二套看似也针对.vue文件,但通过excludedFiles巧妙地排除了所有.vue文件,从而确保其规则只作用于非.vue文件,避免与第一套规则冲突,并防止对TypeScript代码进行重复检查。
确保你的.vue文件正确使用lang=”ts”属性:
立即学习“前端免费学习笔记(深入)”;
<template> </template> <script lang="ts"> // TypeScript代码 </script> <style scoped> /* 样式代码 */ </style>
通过以上配置,ESLint将只对带有lang=”ts”的<script>标签内的TypeScript代码进行检查,而不会干扰项目中的JavaScript代码。 记住安装必要的依赖包:eslint, vue-eslint-parser, @<a style="color:#f60; text-decoration:underline;" title= "typescript"href="https://www.php.cn/zt/15959.html" target="_blank">typescript-eslint/parser,并正确初始化ESLint配置文件。 此方法确保了渐进式TypeScript迁移的平滑过渡。</script>