vite vue-ts 安装eslint + prettier (2023.03)

627 阅读3分钟

因为ESLint的配置经常有变化,一些旧的教程可能已经过时了(有些库和配置已经用不到了,或者配置不生效),所以重新整理了一下

只想看配置的直接看 2 快速流程

开始前,默认你已经使用vue-ts模板初始化了项目

1 完整流程

1.1 安装VSCode插件

安装ESLint和Prettier - Code formatter扩展。

image-20230327175006429.png image-20230327174944887.png

1.2 安装和配置ESLint

  1. 安装ESLint

    npm add -D eslint
    npm add -D eslint-plugin-vue
    npm add -D @typescript-eslint/eslint-plugin
    npm add -D @typescript-eslint/parser
    

    如果使用了Babel,还需要安装

    npm add -D @babel/core
    npm add -D @babel/eslint-parser 
    

    如果使用了ts以及node中的功能如path,还需安装

    yarn add -D  @types/node
    
  2. 安装vite-plugin-eslint(用于eslint结合vite使用)

    在dev时会自动检测ESLint规范,不符合时会在页面和控制台上报错(和vue-cli模式一样)

    npm add -D vite-plugin-eslint
    

    配置vite.config.ts,增加eslintPlugin

    import { defineConfig } from 'vite';
    import vue from '@vitejs/plugin-vue';
    import eslintPlugin from 'vite-plugin-eslint';
    ​
    // https://vitejs.dev/config/
    export default defineConfig({
      plugins: [
        vue(),
        eslintPlugin({
          include: ['src/**/*.ts', 'src/**/*.vue', 'src/*.ts', 'src/*.vue'],
        }),
      ]
    });
    
  3. 在项目根目录下创建.eslintrc.cjs文件

    module.exports = {
      'env': {
        'browser': true,
        'es2021': true,
        'node': true
      },
      'extends': [
        'eslint:recommended',
        'plugin:@typescript-eslint/recommended',
        'plugin:vue/vue3-recommended'
      ],
      'overrides': [
      ],
      'parser': 'vue-eslint-parser',
      'parserOptions': {
        'ecmaVersion': 2020,
        'sourceType': 'module',
        'parser': '@typescript-eslint/parser',
      },
      'plugins': [
        'vue',
        '@typescript-eslint'
      ],
      'rules': {
        'no-console': process.env.NODE_ENV === 'production' ? ['error', { allow: ['error', 'warn'] }] : 'off', //生产模式不允许使用log
        'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off', //生产默认不允许使用debugger
        '@typescript-eslint/no-unused-vars': ['error', { varsIgnorePattern: '.*', args: 'none' }], //变量声明未使用
        '@typescript-eslint/no-explicit-any': 'off' // 允许ts使用any
      }
    }
    

1.3 安装和配置Prettier

  1. 安装Prettier

    npm add -D prettier
    npm add -D eslint-config-prettier
    npm add -D eslint-plugin-prettier
    
    • eslint-config-prettier:兼容插件,用于禁用ESLint中与Prettier冲突的配置项
    • eslint-plugin-prettier:用于让ESlint可以提示Prettier的规则
  2. 修改.eslintrc.cjs,在extends最后一行增加plugin:prettier/recommended

    module.exports = {
      ...
      'extends': [
        'eslint:recommended',
        'plugin:@typescript-eslint/recommended',
        'plugin:vue/vue3-recommended',
        'plugin:prettier/recommended', // <-- this
      ]
    }
    

    一些旧的教程会配很多个prettier,现在只需要配一个就可以了(在eslint-plugin-prettier中已经配置好了)

    github.com/prettier/es…

    究竟是plugin:prettier/recommended做什么的?好吧,这就是它的扩展:

    {
      "extends": ["prettier"],
      "plugins": ["prettier"],
      "rules": {
       "prettier/prettier": "error",
       "arrow-body-style": "off",
       "prefer-arrow-callback": "off"
    }
    
  3. 配置Prettier,有2种方式

    1. 通过独立文件

      以JSON格式配置为例,在项目根目录创建.prettierrc,修改后必须重启vscode才会生效

      具体配置项参考Prettier官网

      {
        "printWidth": 150,
        "singleQuote": true,
        "semi": false,
        "arrowParens": "avoid",
        "endOfLine": "auto",
        "trailingComma": "none"
      }
      
      • 如果VSCode插件识别不到.prettierrc的话(没有语法提示、波浪线),需要修改VSCode设置Prettier: Config Path为对应文件名:.prettierrc

        image-20230327172042736.png

      • 默认ESLint提示Prettier规则是error,如需修改,在.eslintrc.cjs配置中的rules里增加一行

        rules: {
          ...
          'prettier/prettier': 'warn'
        }
        
    2. 直接.eslintrc.cjs中配置

      ⚠️不推荐这种写法,配置不能被VSCode扩展捕获,没有代码提示

      修改根目录中.eslintrc.cjs的内容如下,在rules中增加一行

      'rules': {
          ...
          'prettier/prettier': [
            'error',
            {
              // 一行最多多少个字符
              printWidth: 150,
              // 是否使用单引号
              singleQuote: true,
              // 在语句末尾是否需要分号
              semi: false,
              // 在单独的箭头函数参数周围包括括号 
              arrowParens: 'avoid',
              // 换行符方式
              endOfLine: 'auto'
            }
          ]
        }
      
  4. 创建 .prettierignore,用于排除不需要Prettier规则的文件

    /dist/*
    .local
    .output.js
    /node_modules/**
    ​
    **/*.svg
    **/*.sh
    ​
    /public/*
    /lib/**
    ​
    .eslintrc.cjs
    

2 快速流程

  1. 安装依赖

    npm add -D eslint eslint-plugin-vue @typescript-eslint/eslint-plugin @typescript-eslint/parser @types/node vite-plugin-eslint prettier eslint-config-prettier eslint-plugin-prettier
    

    如果使用了Babel,还需要安装

    npm add -D @babel/core @babel/eslint-parser
    
  2. 根目录创建.eslintrc.cjs

    module.exports = {
      'env': {
        'browser': true,
        'es2021': true,
        'node': true
      },
      'extends': [
        'eslint:recommended',
        'plugin:@typescript-eslint/recommended',
        'plugin:vue/vue3-recommended',
        'plugin:prettier/recommended',
    ],
      'overrides': [
      ],
      'parser': 'vue-eslint-parser',
      'parserOptions': {
        'ecmaVersion': 2020,
        'sourceType': 'module',
        'parser': '@typescript-eslint/parser',
      },
      'plugins': [
        'vue',
        '@typescript-eslint'
      ],
      'rules': {
        'no-console': process.env.NODE_ENV === 'production' ? ['error', { allow: ['error', 'warn'] }] : 'off', //生产模式不允许使用log
        'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off', //生产默认不允许使用debugger
        '@typescript-eslint/no-unused-vars': ['error', { varsIgnorePattern: '.*', args: 'none' }], //变量声明未使用
        '@typescript-eslint/no-explicit-any': 'off', // 允许ts使用any
        'prettier/prettier': 'warn'
      }
    }
    
  3. 根目录创建.prettierrc

    {
      "printWidth": 150,
      "singleQuote": true,
      "semi": false,
      "arrowParens": "avoid",
      "endOfLine": "auto",
      "trailingComma": "none"
    }
    
  4. 根目录创建.prettierignore

    /dist/*
    .local
    .output.js
    /node_modules/**
    
    **/*.svg
    **/*.sh
    
    /public/*
    /lib/**
    
    .eslintrc.cjs