安装
使用npm install --save-dev eslint来安装eslint
npm install --save-dev eslint
初始化
使用npx eslint --init
命令初始化eslint
npx eslint --init
会弹出eslint配置让你选择,以下是我的配置:
You can also run this command directly using 'npm init @eslint/config'.
? How would you like to use ESLint? ...
To check syntax and find problems //, 发现问题, 强制代码风格
? What type of modules does your project use? ...
JavaScript modules (import/export)
? Which framework does your project use? ...
Vue.js
? Does your project use TypeScript? » No / Yes //这里看你项目是否使用ts
Yes
? Where does your code run? ... (用空格选中两个,回车确定)
√ Browser
√ Node
? What format do you want your config file to be in? ... //ESLint 的配置文件格式
JavaScript
? Which package manager do you want to use? …
npm
? Would you like to install them now? › No / Yes
Yes
安装完成后在项目根目录出现eslint.config.js文件:
import globals from "globals";
import pluginJs from "@eslint/js";
import tseslint from "typescript-eslint";
import pluginVue from "eslint-plugin-vue";
/** @type {import('eslint').Linter.Config[]} */
export default [
{
files: ["**/*.{js,mjs,cjs,ts,vue}"],
},
{ languageOptions: { globals: globals.browser } },
pluginJs.configs.recommended,
...tseslint.configs.recommended,
...pluginVue.configs["flat/essential"],
{ files: ["**/*.vue"], languageOptions: { parserOptions: { parser: tseslint.parser } } }
];
需要在eslint.config.js中添加以下配置,不然会报错:
Error while loading rule '@typescript-eslint/no-unused-expressions': Cannot read properties of undefined (reading 'allowShortCircuit')
rules: {
"@typescript-eslint/no-unused-expressions": [
"error",
{ allowShortCircuit: true, allowTernary: false, allowTaggedTemplates: false }
]
}
添加以后的eslint.config.js是这样:
import globals from "globals";
import pluginJs from "@eslint/js";
import tseslint from "typescript-eslint";
import pluginVue from "eslint-plugin-vue";
/** @type {import('eslint').Linter.Config[]} */
export default [
{
files: ["**/*.{js,mjs,cjs,ts,vue}"],
//添加在这里
rules: {
"@typescript-eslint/no-unused-expressions": [
"error",
{ allowShortCircuit: true, allowTernary: false, allowTaggedTemplates: false }
]
}
},
{ languageOptions: { globals: globals.browser } },
pluginJs.configs.recommended,
...tseslint.configs.recommended,
...pluginVue.configs["flat/essential"],
{ files: ["**/*.vue"], languageOptions: { parserOptions: { parser: tseslint.parser } } }
];
其他的规则(可自行选择):
"rules": {
'semi': ['warn', 'never'], // 禁止尾部使用分号
'no-console': 'warn', // 禁止出现console
'no-debugger': 'warn', // 禁止出现debugger
'no-duplicate-case': 'warn', // 禁止出现重复case
'no-empty': 'warn', // 禁止出现空语句块
'no-extra-parens': 'warn', // 禁止不必要的括号
'no-func-assign': 'warn', // 禁止对Function声明重新赋值
'no-unreachable': 'warn', // 禁止出现[return|throw]之后的代码块
'no-else-return': 'warn', // 禁止if语句中return语句之后有else块
'no-empty-function': 'warn', // 禁止出现空的函数块
'no-lone-blocks': 'warn', // 禁用不必要的嵌套块
'no-multi-spaces': 'warn', // 禁止使用多个空格
'no-redeclare': 'warn', // 禁止多次声明同一变量
'no-return-assign': 'warn', // 禁止在return语句中使用赋值语句
'no-return-await': 'warn', // 禁用不必要的[return/await]
'no-self-compare': 'warn', // 禁止自身比较表达式
'no-useless-catch': 'warn', // 禁止不必要的catch子句
'no-useless-return': 'warn', // 禁止不必要的return语句
'no-mixed-spaces-and-tabs': 'warn', // 禁止空格和tab的混合缩进
'no-multiple-empty-lines': 'warn', // 禁止出现多行空行
'no-trailing-spaces': 'warn', // 禁止一行结束后面不要有空格
'no-useless-call': 'warn', // 禁止不必要的.call()和.apply()
'no-var': 'warn', // 禁止出现var用let和const代替
'no-delete-var': 'off', // 允许出现delete变量的使用
'no-shadow': 'off', // 允许变量声明与外层作用域的变量同名
'dot-notation': 'warn', // 要求尽可能地使用点号
'default-case': 'warn', // 要求switch语句中有default分支
'eqeqeq': 'warn', // 要求使用 === 和 !==
'curly': 'warn', // 要求所有控制语句使用一致的括号风格
'space-before-blocks': 'warn', // 要求在块之前使用一致的空格
'space-in-parens': 'warn', // 要求在圆括号内使用一致的空格
'space-infix-ops': 'warn', // 要求操作符周围有空格
'space-unary-ops': 'warn', // 要求在一元操作符前后使用一致的空格
'switch-colon-spacing': 'warn', // 要求在switch的冒号左右有空格
'arrow-spacing': 'warn', // 要求箭头函数的箭头前后使用一致的空格
'array-bracket-spacing': 'warn', // 要求数组方括号中使用一致的空格
'brace-style': 'warn', // 要求在代码块中使用一致的大括号风格
'camelcase': 'warn', // 要求使用骆驼拼写法命名约定
'indent': ['warn', 4], // 要求使用JS一致缩进4个空格
'max-depth': ['warn', 4], // 要求可嵌套的块的最大深度4
'max-statements': ['warn', 100], // 要求函数块最多允许的的语句数量20
'max-nested-callbacks': ['warn', 3], // 要求回调函数最大嵌套深度3
'max-statements-per-line': ['warn', { max: 1 }], // 要求每一行中所允许的最大语句数量
"quotes": ["warn", "single", "avoid-escape"], // 要求统一使用单引号符号
"vue/require-default-prop": 0, // 关闭属性参数必须默认值
"vue/singleline-html-element-content-newline": 0, // 关闭单行元素必须换行符
"vue/multiline-html-element-content-newline": 0, // 关闭多行元素必须换行符
// 要求每一行标签的最大属性不超五个
'vue/max-attributes-per-line': ['warn', { singleline: 5 }],
// 要求html标签的缩进为需要4个空格
"vue/html-indent": ["warn", 4, {
"attribute": 1,
"baseIndent": 1,
"closeBracket": 0,
"alignAttributesVertically": true,
"ignores": []
}],
// 取消关闭标签不能自闭合的限制设置
"vue/html-self-closing": ["error", {
"html": {
"void": "always",
"normal": "never",
"component": "always"
},
"svg": "always",
"math": "always"
}]
}
插件及vite配置
vite-plugin-eslint
用于vite运行的时候自动检测eslint规范
npm install --save-dev vite-plugin-eslint
eslint-parser
npm install --save-dev @babel/core @babel/eslint-parser
vite配置
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";
import eslint from "vite-plugin-eslint";
export default defineConfig({
plugins: [
vue(),
// 增加下面的配置项
eslint({
include: ["src/**/*.js", "src/**/*.vue", "src/*.js", "src/*.vue"]
})
],
resolve: {
alias: {
"@": resolve(__dirname, "./src"),
"@components": resolve(__dirname, "./src/components"),
"@views": resolve(__dirname, "./src/views")
},
extensions: [".js", ".ts", ".json", ".vue"]
}
});
安装prettier
npm install --save-dev prettier
安装完成以后根目录会出现.prettierrc文件(没有就自己创建),下面是常见的配置,可自行选择:
{
"printWidth": 80, // 指定行的最大长度
"tabWidth": 2, // 指定缩进的空格数
"useTabs": false, // 是否使用制表符进行缩进,默认为 false
"singleQuote": true, // 是否使用单引号,默认为 false
"quoteProps": "as-needed", // 对象属性是否使用引号,默认为 "as-needed"
"trailingComma": "none", // 是否使用尾随逗号(末尾的逗号),可以是 "none"、"es5"、"all" 三个选项
"bracketSpacing": true, // 对象字面量中的括号是否有空格,默认为 true
"jsxBracketSameLine": false, // JSX 标签的右括号是否与前一行的末尾对齐,默认为 false
"arrowParens": "always", // 箭头函数参数是否使用圆括号,默认为 "always"
"rangeStart": 0, // 指定格式化的范围的起始位置
"rangeEnd": Infinity, // 指定格式化的范围的结束位置
"requirePragma": false, // 是否需要在文件顶部添加特殊的注释才能进行格式化,默认为 false
"insertPragma": false, // 是否在格式化后的文件顶部插入特殊的注释,默认为 false
"proseWrap": "preserve", // 是否保留 markdown 文件中的换行符,默认为 "preserve"
"htmlWhitespaceSensitivity": "css", // 指定 HTML 文件中空格敏感度的配置选项,可以是 "css" 或 "strict" 两个选项
"vueIndentScriptAndStyle": false, // 是否缩进 Vue 文件中的 <script> 和 <style> 标签,默认为 false
"endOfLine": "auto", // 指定换行符的风格,可以是 "auto"、"lf"、"crlf"、"cr" 四个选项
"semi": true, // 行末是否添加分号,默认为 true
"usePrettierrc": true, // 是否使用项目根目录下的 .prettierrc 文件,默认为 true
"overrides": [ // 针对特定文件或文件类型的格式化配置
{
"files": "*.json", // 匹配的文件或文件类型
"options": {
"tabWidth": 4 // 针对该文件类型的配置选项
}
},
{
"files": "*.md",
"options": {
"printWidth": 100
}
}
]
}
配置VSCode
安装“ESLint”插件
安装Prettier ESLint
依赖
整个流程下来安装的依赖:
"@babel/core": "^7.26.0",
"@babel/eslint-parser": "^7.25.9",
"@eslint/js": "^9.15.0",
"@typescript-eslint/eslint-plugin": "^8.14.0",
"@typescript-eslint/parser": "^8.14.0",
"eslint": "^9.15.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.2.1",
"eslint-plugin-vue": "^9.31.0",
"globals": "^15.12.0",
"prettier": "^3.3.3",
"typescript-eslint": "^8.14.0",
"vite-plugin-eslint": "^1.8.1",
可能遇到的问题
Could not find config file. Plugin: vite-plugin-eslint
解决办法:参考:https://blog.csdn.net/m0_53022813/article/details/137379480
Cannot read properties of undefined (reading 'allowShortCircuit')
解决办法:初始化