vue中配置Eslint的步骤代码解析
作者:白桃与猫
本文介绍Vue项目中配置ESLint和Prettier的步骤,包括安装依赖、创建配置文件、设置package.json脚本、格式化配置及运行检查,实现代码规范,感兴趣的朋友一起看看吧
1. 安装ESLint相关依赖
# 安装ESLint核心包 npm install --save-dev eslint # 安装Vue相关插件 npm install --save-dev eslint-plugin-vue vue-eslint-parser # 安装JavaScript推荐配置 npm install --save-dev @eslint/js globals # 安装Prettier相关(用于代码格式化) npm install --save-dev prettier eslint-plugin-prettier
2. 创建ESLint配置文件
import globals from 'globals';
import pluginJs from '@eslint/js';
import pluginVue from 'eslint-plugin-vue';
import vueParser from 'vue-eslint-parser';
import prettier from 'eslint-plugin-prettier';
export default [
// 全局忽略配置
{
ignores: [
'**/*.config.js',
'dist/**',
'node_modules/**',
'!**/eslint.config.js',
],
},
// JavaScript文件配置
{
files: ['**/*.js', '**/*.mjs'],//针对.js和.mjs文件
languageOptions: {
globals: globals.browser,
ecmaVersion: 'latest',
sourceType: 'module',
},
plugins: {
prettier,
},
rules: {
'prettier/prettier': 'error',
'no-var': 'error',// 禁止使用var
'no-multiple-empty-lines': ['warn', { max: 1 }],//最多允许1个空行
'no-console': 'warn',//禁止使用console
'no-debugger': 'warn',//禁止使用debugger
'no-unexpected-multiline': 'error',//防止意外的多行语句
'no-useless-escape': 'off',//关闭对不必要转义字符的检查
'no-unused-vars': 'error',//禁止未使用的变量
},
},
// Vue文件配置
{
files: ['**/*.vue'],
languageOptions: {
globals: globals.browser,
parser: vueParser,
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
ecmaFeatures: {
jsx: true,
},
},
},
plugins: {
prettier,
vue: pluginVue,
},
rules: {
'prettier/prettier': 'error',
'no-var': 'error',
'no-multiple-empty-lines': ['warn', { max: 1 }],
'no-console': 'warn',
'no-debugger': 'warn',
'no-unexpected-multiline': 'error',
'no-useless-escape': 'off',
'no-unused-vars': 'error',
// Vue特定规则
'vue/multi-word-component-names': 'off',//关闭组件名必须时多词的要求
'vue/script-setup-uses-vars': 'error',//确保<script setup>中变量被正确使用
'vue/no-mutating-props': 'off',
'vue/attribute-hyphenation': 'off',
'vue/valid-v-slot': [
'error',
{
allowModifiers: true,
},
],
},
},
// 推荐配置
pluginJs.configs.recommended,//将使用区推荐的有关JavaScript的ESLint规则
...pluginVue.configs['flat/essential'],// 使用Vue.js的基本ESLint规则
];3. 配置package.json脚本
{
"scripts": {
"lint": "eslint . --fix",
"lint:check": "eslint .",
"format": "prettier --write ."
}
}4. 创建prettier配置文件
对代码进行格式化配置
{
"semi": true,// 在每个语句的末尾添加分号
"singleQuote": true,// 使用单引号
"tabWidth": 2,// 设置缩进的空格数为2
"useTabs": false,// 使用空格缩进
"printWidth": 100,//每行的最大字符数为100
"trailingComma": "all"//在多行结构的最后一个元素后添加逗号
}5. 运行后检查
# 检查代码 npm run lint:check # 检查并自动修复 npm run lint # 格式化代码 npm run format
到此这篇关于vue中配置Eslint的步骤的文章就介绍到这了,更多相关vue配置Eslint内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
