项目工程化配置---eslint(v9.x.x)/prettierrc篇

1,057 阅读2分钟

在新建vite+vue3+ts项目后需要对项目工程化进行配置,为了利于代码规范

正好eslint版本更新到v9.x.x,所以这里才用最新的eslint9进行相关配置

不说废话,先贴代码

eslint.config.js

// 引入vue模版的eslint
import pluginVue from 'eslint-plugin-vue'
import eslint from '@eslint/js'
// ts-eslint解析器,使 eslint 可以解析 ts 语法
import tseslint from 'typescript-eslint'
// vue文件解析器
import vueParser from 'vue-eslint-parser'
export default tseslint.config({
  // tseslint.config添加了extends扁平函数,直接用。否则是eslint9.0版本是没有extends的
  extends: [
    eslint.configs.recommended,
    ...tseslint.configs.recommended,
    ...pluginVue.configs['flat/essential'] // vue3推荐的eslint配置
  ],
  languageOptions: {
    parser: vueParser, // 使用vue解析器,这个可以识别vue文件
    parserOptions: {
      parser: tseslint.parser, // 在vue文件上使用ts解析器
      sourceType: 'module'
    }
  },
  rules: {
    'semi': ['warn', 'never'],
    "comma-dangle": ["error", "never"],
    "no-unused-vars": 2,
    'space-before-function-paren': 0,
    'generator-star-spacing': 'off',
    'object-curly-spacing': 0, // 强制在大括号中使用一致的空格
    'array-bracket-spacing': 0, // 方括号
    "@typescript-eslint/no-explicit-any": ["off"]
  },
  ignores: ["dist/**", "node_modules/**", "*.d.ts"]
})

然后是prettierrc的配置

.prettierrc.json

{
  "$schema": "https://json.schemastore.org/prettierrc",
  "semi": false,
  "tabWidth": 2,
  "singleQuote": true,
  "printWidth": 100,
  "trailingComma": "none"
}

补充一下,这里的配置根据自己项目情况来,我是觉得这几个基本配置项已经够用了,所以没有写一大堆不常用的配置项

再然后是到vite的配置

import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import eslint from 'vite-plugin-eslint'

// https://vitejs.dev/config/
export default defineConfig({
  base: './',
  plugins: [
    vue(),
    vueJsx(),
    {
      ...eslint({
        failOnWarning: false,
        failOnError: false
      })
    }
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  server: {
    proxy: {
      '^/api': {
        target: 'http://api.com',
        changeOrigin: true,
        rewrite: (path) => path.replace('/^/api/', '/api')
      }
    }
  }
})

再然后是补充说明,因为使用最新的eslint的配置,有些配置项是和以前版本不太一样的,在此记录下我在初次配置时被卡住的点:

1.tsconfig.node.json

moduleResolution配置项 "moduleResolution": "node",之前默认的配置是"moduleResolution": "Bundler",但是使用原来的默认配置就会导致vite.config.ts的引入eslint报错,我在网上查询了很多文章,暂时没有其他比较好的解决办法,经过实践后改成"moduleResolution": "node"也是可以正常使用的;

2.eslint.config.js

ignores:eslint的忽略配置项,在最新的eslint官方文档中是这么写的: eslint.org.cn/docs/latest…

非全局 ignores 模式只能匹配文件名。如 "dir-to-exclude/" 的模式不会忽略任何内容。若要忽略特定目录中的所有内容,应使用如 "dir-to-exclude/**" 的模式。

所以在eslint.config.js里面添加下面的配置项即可正常使用:

ignores: ["dist/**", "*.d.ts"] 否则会对dist文件夹也进行格式化检查(以忽略dist文件夹为例)

结语

以上就是在使用最新版本的工程化配置说明和一些注意点,后续可能还会保持更新~