安装
kotlin
npm init @eslint/config@latest

经过上述操作会安装 eslint 必要的包以及生成 eslint.config.js 配置文件
插件
编辑器插件的作用是在编辑器里实时运行 ESLint 包来检查并自动修复代码
安装
dbaeumer.vscode-eslint
配置
json
// settings.json
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit",
},
"eslint.validate": ["javascript", "typescript", "vue"],
}
配置文件
配置文件采用扁平化配置,该配置方式是 eslint v9 的新配置系统
- 扁平化配置采用数组形式,数组中的每个对象都是一个配置对象
- 每个配置对象都包含一套完整的 eslint 规则、文件匹配模式和其他配置选项
- 多配置对象间的规则合并
- 遍历配置对象数组,根据 files 和 ignores 决定文件是否匹配该配置对象
- 无 files 配置则匹配所有文件
- 遍历结束,若存在多个配置对象,则后者的规则覆盖前者
- 遍历配置对象数组,根据 files 和 ignores 决定文件是否匹配该配置对象
js
// eslint.config.js
import js from "@eslint/js";
import globals from "globals";
import tseslint from "typescript-eslint";
import pluginVue from "eslint-plugin-vue";
import { defineConfig } from "eslint/config";
export default defineConfig([
{
files: ["**/*.{js,mjs,cjs,ts,mts,cts,vue}"],
plugins: { js },
extends: ["js/recommended"],
languageOptions: { globals: { ...globals.browser, ...globals.node } },
},
tseslint.configs.recommended,
pluginVue.configs["flat/essential"],
{
files: ["**/*.vue"],
languageOptions: { parserOptions: { parser: tseslint.parser } },
}
]);
prettier
eslint 侧重于代码质量,prettier 侧重于代码风格检查,将 prettier 作为 eslint 的插件,通过 eslint 统一管理代码质量和格式
安装依赖
arduino
pnpm add eslint-plugin-prettier eslint-config-prettier -D
- eslint-config-prettier: 关闭 eslint 中有关代码格式化的配置
- eslint-plugin-prettier: 把 prettier 配置成 eslint 的一个插件
修改 eslint 配置文件
js
// eslint.config.js
...
import eslintConfigPrettier from "eslint-config-prettier";
import eslintPluginPrettier from "eslint-plugin-prettier/recommended";
export default defineConfig([
...
eslintPluginPrettier,
eslintConfigPrettier,
]);