vue3+ts+eslint+prettier 实现代码风格统一

59 阅读4分钟

vue3+ts+eslint+prettier 实现代码风格统一

一.安装eslint

npm i eslint -D

1.初始化eslint

当前文章是基于 eslint9.39.2 版本创作

创建eslint配置文件,eslint8.21.0之后可以使用eslint.config.js文件名。

或使用命令初始化eslint配置文件

npx eslint --init

1)安装@eslint/config@lates image.png 2)选择要检测的文件 image.png 3)选择如何使用eslint image.png 4)选择使用哪种模块类型 image.png 5)框架选择 image.png 6)是否使用ts image.png 7)选择运行环境 image.png 8)希望配置文件用什么语法 image.png 9)选择要安装解析相关依赖包 image.png 10)选择希望使用的安装包工具 image.png

2.修改eslint.config.js中的相关配置
import pluginJs from '@eslint/js';
import tseslint from 'typescript-eslint';
import pluginVue from 'eslint-plugin-vue';
import prettier from 'eslint-plugin-prettier';
import prettierConfig from 'eslint-config-prettier';
import eslintparser from 'vue-eslint-parser';
export default [
  {
    files: ['**/*.{js,mjs,cjs,vue}'],
    ignores: [
        'node_modules/**', 
        'dist/**', 
        'public/**', 
        'coverage/**', 
        'src/assets/**'
    ],
    languageOptions: {
      globals: globals.browser,
      parser: eslintparser,
      parserOptions: {
        ecmaVersion: 2020,
        sourceType: 'module',
        parser: '@typescript-eslint/parser',
        ecmaFeatures: {
          jsx: true,
        },
      },
    },
  },

  pluginJs.configs.recommended,
  ...tseslint.configs.recommended,
  ...pluginVue.configs['flat/essential'],
  ...pluginVue.configs['flat/recommended'],
  prettierConfig, // 解决prettier和eslint的冲突
  {
    plugins: {
      prettier: prettier, // 使用prettier格式化
    },
    rules: {
      // 开启这条规则后,会将prettier的校验规则传递给eslint,这样eslint就可以按照prettier的方式来进行代码格式的校验
      'prettier/prettier': 'error',
      'no-var': 'error', // 要求使用 let 或 const 而不是 var
      'no-console': 'off',
      'no-restricted-globals': 'off',
      'no-restricted-syntax': 'off',
      'vue/multi-word-component-names': 'off', // 禁用vue文件强制多个单词命名
      'no-multiple-empty-lines': ['warn', { max: 1 }],
      'vue/valid-template-root': 'off',
      'no-unused-vars': 'off',
      'no-undef': 'off', // 自动引入vue和UI组件库报错问题
      '@typescript-eslint/no-unused-vars': 'off', // 关闭未使用变量规则
      '@typescript-eslint/no-explicit-any': 'off', // 关闭ts中any校验
      semi: ['error', 'always'],
      'no-debugger': 'warn', //提交时不允许有debugger
      'no-console': [
        //提交时不允许有console.log
        'warn',
        {
          allow: ['warn', 'error'],
        },
      ],
    },
  },
];

3.修改vite.config.ts
// 引入vite-plugin-eslint 
import eslintPlugin from 'vite-plugin-eslint' 
// 配置plugins 
eslintPlugin({ 
    include: ['src/**/*.js', 'src/**/*.vue'], 
    cache: true, 
}),

4.命令行式运行:修改 package.json
{ 
... 
"scripts": { 
    ... 
    "eslint:comment": "使用 ESLint 检查并自动修复 src 目录下所有扩展名为 .js 和 .vue 的文件", 
    "eslint": "eslint --ext .js,.vue --ignore-path .gitignore --fix src",//旧版 
    "eslint": "eslint \"src/**/*.{js,ts,vue}\" --fix",//新版 } 
... 
}
5.注意

eslintignore文件已经废除,新版本的gnore写在eslint.config.js中

image.png

二.安装prettier

1.安装

npm i prettier -D

npm i eslint-config-prettier -D

cnpm i eslint-plugin-prettier -D

2.创建配置文件: .prettierrc.js
// 一行最多 120 字符 
printWidth: 120, 
// 使用 2 个空格缩进
tabWidth: 2, 
// 不使用 tab 缩进,而使用空格 
useTabs: false, 
// 行尾需要有分号 
semi: true, 
// 使用单引号代替双引号 
singleQuote: true,
// 对象的 key 仅在必要时用引号 
quoteProps: 'as-needed', 
// jsx 不使用单引号,而使用双引号 
jsxSingleQuote: false, 
// 末尾使用逗号 
trailingComma: 'all', 
// 大括号内的首尾需要空格{ foo: bar }
bracketSpacing: true, 
// jsx 标签的反尖括号需要换行 
jsxBracketSameLine: false, 
// 箭头函数,只有一个参数的时候,也需要括号 
arrowParens: 'always', 
// 每个文件格式化的范围是文件的全部内容 
rangeStart: 0, 
rangeEnd: Infinity, 
// 不需要写文件开头的 
@prettier requirePragma: false, 
// 不需要自动在文件开头插入 
@prettier insertPragma: false, 
// 使用默认的折行标准 
proseWrap: 'preserve', 
// 根据显示样式决定 html 要不要折行 
htmlWhitespaceSensitivity: 'css', 
// 换行符使用 lf endOfLine: 'auto' 
}
3.修改 eslint.config.js 配置,添加prettier
import prettier from 'eslint-plugin-prettier' 
export default [ 
        ...
        { 
        plugins: {
            prettier: prettier,
        }, 
        rules: { 
            'prettier/prettier': 'error', 
        ... 
        }, 
    }, 
]
4.命令行式运行:修改 package.json
{ 
    ... 
    "scripts": { 
        ... 
        "prettier:comment": "自动格式化当前目录下的所有文件", 
        "prettier": "prettier --write" 
        } 
    ... 
}
5.解决eslint和pretter中的冲突
// eslint.config.js 
import prettier from 'eslint-plugin-prettier' 
import prettierConfig from'eslint-config-prettier'; 
export default [ 
    .... 
    // 插件的默认推荐配置需要直接包含在配置数组中 
    prettierConfig, 
    { 
        plugins: { 
            prettier: prettier, //解决prettier和eslint的冲突 
        }, 
        rules: { 
            'prettier/prettier': 'error', 
            ... 
        }, 
    }, 
]

三.创建.vscode文件夹

在项目的根目录创建文件夹.vscode,再在目录中创建settings.json文件。将如下代码拷其中

{ 
"editor.formatOnSave": true, // 核心:保存时自动格式化 
"editor.quickSuggestions": true,// 启用代码提示
"eslint.enable": true, //启用 ESLint 插件 
//ESLint 应该验证哪些文件类型 
"eslint.validate": [
    "javascript", 
    "javascriptreact", 
    "vue-html", 
    "typescript", 
    "html", 
    "vue"
 ], 
"eslint.options": { 
    // 检查这些文件类型
    "extensions": [".js", ".jsx", ".ts", ".tsx", ".vue"] 
 },
// 可选:保存时先修复代码问题(如ESLint报错)再格式化(前端常用) 
"editor.codeActionsOnSave": { 
    "source.fixAll": true
}, 
// 可选:指定默认格式化工具(比如前端优先用Prettier) 
"editor.defaultFormatter": "esbenp.prettier-vscode" ,
"[vue]": { 
    "editor.defaultFormatter": "esbenp.prettier-vscode"
    }, 
"[typescript]": { 
    "editor.defaultFormatter": "esbenp.prettier-vscode" 
    }
}