精準(zhǔn)配置ESLint,僅檢查vue組件中的typescript代碼
在逐步將老項(xiàng)目遷移到TypeScript的過(guò)程中,如何配置ESLint只檢查.vue文件中使用TypeScript ( lang=”ts” ) 的部分,而忽略JavaScript代碼,是一個(gè)常見(jiàn)的難題。本文提供一種有效的ESLint配置方案,避免overrides配置的常見(jiàn)誤區(qū)。
首先,在.eslintrc.JS文件中進(jìn)行如下配置:
module.exports = { // ...其他配置... overrides: [ { files: ['*.vue'], parser: 'vue-eslint-parser', parserOptions: { parser: '@typescript-eslint/parser', }, rules: { // TypeScript相關(guān)的ESLint規(guī)則 }, }, { files: ['*.vue'], //關(guān)鍵:排除所有.vue文件,避免重復(fù)檢查 excludedFiles: ['**/*.vue'], parser: 'vue-eslint-parser', parserOptions: { parser: 'espree', ecmaVersion: 2020, sourceType: 'module', }, rules: { // JavaScript相關(guān)的ESLint規(guī)則 (不會(huì)應(yīng)用于TypeScript代碼) }, }, ], };
此配置利用overrides定義兩套規(guī)則:第一套針對(duì).vue文件中的TypeScript代碼;第二套看似也針對(duì).vue文件,但通過(guò)excludedFiles巧妙地排除了所有.vue文件,從而確保其規(guī)則只作用于非.vue文件,避免與第一套規(guī)則沖突,并防止對(duì)TypeScript代碼進(jìn)行重復(fù)檢查。
確保你的.vue文件正確使用lang=”ts”屬性:
立即學(xué)習(xí)“前端免費(fèi)學(xué)習(xí)筆記(深入)”;
<template> </template> <script lang="ts"> // TypeScript代碼 </script> <style scoped> /* 樣式代碼 */ </style>
通過(guò)以上配置,ESLint將只對(duì)帶有l(wèi)ang=”ts”的<script>標(biāo)簽內(nèi)的TypeScript代碼進(jìn)行檢查,而不會(huì)干擾項(xiàng)目中的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配置文件。 此方法確保了漸進(jìn)式TypeScript遷移的平滑過(guò)渡。</script>