前言
最近发现公司的项目代码修改保存后,代码会自动进行格式化。但是自己搭建的小项目不能进行格式化,虽然安装了一个格式化插件,但是格式化的效果很不舒服。
实现
安装eslint插件
上面只是在vscode里安装了,实际项目里还需要安装
npm install eslint babel-eslint -D
生产配置文件
./node_modules/.bin/eslint --init
运行完会有以下提示:
你要如何使用ESLint,选择第三个
看自己项目的实际情况,我的项目用的第一个
项目是否用了框架,我选择的第二个
是否使用ts
输入a选择全部
选择第一个
选择标准,我用的第二个
创建的配置文件的格式,我用的第一个
上面完成之后会安装依赖并生成下面的两个文件
.eslintignore
告诉 ESLint 去忽略特定的文件和目录。.eslintignore 文件是一个纯文本文件,其中的每一行都是一个 glob 模式表明哪些路径应该忽略检测
.eslintrc.js
校验规则这些都有了后,可以看到
现在还没完,改一下校验规则,把下面的代码替换掉.eslintrc.js
原有代码
vue2.x + js
module.exports = {
// 此项是用来告诉eslint找当前配置文件不能往父级查找
root: true,
// 运行环境
env: {
browser: true,
node: true // node 环境
},
// 此项是用来指定eslint解析器的,解析器必须符合规则,babel-eslint解析器是对babel解析器的包装使其与ESLint解析
parserOptions: {
parser: 'babel-eslint',
// 指定js版本。语法上的支持
ecmaVersion: 6
},
// 此项是用来配置标准的js风格,就是说写代码的时候要规范的写
extends: [
'plugin:vue/vue3-essential',
'eslint:recommended',
],
/*
下面这些rules是用来设置从插件来的规范代码的规则,使用必须去掉前缀eslint-plugin-
主要有如下的设置规则,可以设置字符串也可以设置数字,两者效果一致
"off" -> 0 关闭规则
"warn" -> 1 开启警告规则
"error" -> 2 开启错误规则
*/
rules: {
//属性属性
'vue/attributes-order': 1,
"vue/order-in-components": ["error", {
"order": [
"el",
"name",
"parent",
"functional",
["delimiters", "comments"],
["components", "directives", "filters"],
"extends",
"mixins",
"inheritAttrs",
"model",
["props", "propsData"],
"data",
"computed",
"watch",
"LIFECYCLE_HOOKS",
"beforeCreate",
"created",
"mounted",
"beforeDestroy",
"destroyed",
"methods",
["template", "render"],
"renderError"
]
}],
// 关闭
'eqeqeq': [0, 'allow-null'], // 要求使用 === 和 !==
'prefer-const': 0, // 要求使用const声明那些声明后不再被修改的变量
// 警告
'consistent-this': [1, 'that'], // 获取当前执行环境的上下文时,强制使用一致的命名(此处强制使用 'that')。
'no-debugger': 1, // 不使用 debugger
'no-console': 1, // 不使用 console
'no-alert': 1, // 不使用 alert
'comma-dangle': [1, 'never'], // 禁止末尾逗号
'eol-last': 1, // 要求文件末尾存在空行
'vue/html-indent': [2, 4], // html 内 缩进
'vue/no-multi-spaces': [2, { ignoreProperties: false }], // html 属性中不允许出现多个空格
'vue/no-spaces-around-equal-signs-in-attribute': [2], // html 代码中 “=” 前后不能有空格
'vue/prop-name-casing': [2], // 这条规则强制在vue组件(camelCase)中使用正确的支柱外壳。
'vue/require-prop-types': 2, // 在 props 中至少要指定类型
'vue/attribute-hyphenation': [2, 'always'], // 强制在Vue模板中的自定义组件上使用连字符属性名称
'vue/html-closing-bracket-spacing': [2, { // 标签前后空格
'startTag': 'never', // 标签最前面不允许出现空格
'endTag': 'never', // 标签最后面不允许出现空格
'selfClosingTag': 'always' // 自闭合标签 后必须有一个空格
}],
'vue/html-end-tags': [2], // 不允许缺少结束标记。
'vue/html-quotes': [2, 'double'], // html 标签必须使用 双引号
'vue/multiline-html-element-content-newline': [2, { // 内容 不允许出现断行
'ignoreWhenEmpty': true,
'allowEmptyLines': true
}],
'vue/mustache-interpolation-spacing': [2, 'always'], // 插值两端必须留一个空格
'vue/v-bind-style': [2, 'shorthand'], // v-bind 指令必须使用缩写
'vue/v-on-style': [2, 'shorthand'], // v-on 指令必须使用缩写
// "vue/this-in-template": [2, "never"], // 标签内 不需要写this
'vue/component-name-in-template-casing': [2, 'kebab-case', { // 强制 标签使用 中横线间隔
'registeredComponentsOnly': false // 检查所有
}],
'vue/html-closing-bracket-newline': [2, {
'singleline': 'never',
'multiline': 'never'
}],
'semi': [2, 'always'], // 语句后面必须有 分号
'no-label-var': 2, // 不允许标签与变量同名
'no-undef': 2, // 禁止使用未声明的变量。
'no-unused-vars': [1, { 'vars': 'all', 'args': 'after-used', 'ignoreRestSiblings': false }], // 禁止出现未使用的变量
'no-undef-init': 2, // 禁止将变量初始化为undefined
'use-isnan': 2, // 要求使用isNaN()检查NaN
'no-floating-decimal': 2, // 禁止数字字面量中使用前导和末尾小数点
'no-multi-str': 2, // 禁止使用多行字符串
'no-sequences': 2, // 禁用逗号操作符
'yoda': [2, 'never'], // 要求或禁止Yoda条件。 if("red" === color) { //字面量在前,变量在后 } 比较绝不能是Yoda条件(需要变量在前,字面量在后)
'indent': [2, 4, { SwitchCase: 1 }], // 强制使用一致的缩进
'no-mixed-spaces-and-tabs': 2, // 禁止空格和tab的混合缩进
'no-multiple-empty-lines': [2, { max: 2 }], // 禁止出现多行空行 // 最大连续空行数
'no-trailing-spaces': 2, // 禁止行尾空格
'padded-blocks': [2, 'never'], // 函数内不允许开始结束有空行
'no-sparse-arrays': 2, // 禁用稀疏数组
/**
* 强烈使用一致的反勾号``、双引号""或单引号''
* 允许字符串使用单引号或者双引号,只要字符串中包含了一个其他引号,否则需要转义
* 允许字符串使用反勾号
*/
'quotes': [2, 'single', { avoidEscape: true, allowTemplateLiterals: true }],
'curly': [2, 'all'], // 强制所有控制语句使用一致的括号风格, 不能省略大括号
// 强制
'no-dupe-keys': 2, // 禁止对象字面量中出现重复的key
'no-duplicate-case': 2, // 禁止出现重复的case标签
'no-ex-assign': 2, // 禁止对catch子句的参数重新赋值
'no-unreachable': 2, // 禁止在return、throw、continue、break语句之后出现不可达代码
'valid-typeof': 2, // 强制typeof表达式与有效的字符串进行比较
'dot-location': [2, 'property'], // 强制在点号之前和之后一致的换行
'no-empty-pattern': 2, // 禁止使用空解构模式
'no-eval': 2, // 禁止eval()
'no-implied-eval': 2, // 禁止使用类似eval()的方法
'no-extend-native': 2, // 禁止扩展原生类型
'no-fallthrough': 2, // 禁止case语句落空
'no-lone-blocks': 2, // 禁用不必要嵌套块
'no-new-wrappers': 2, // 禁止对String,Number 和 Boolean 使用new操作符
'no-redeclare': 2, // 禁止多次声明同一变量
'no-return-assign': [2, 'except-parens'], // 禁止在return语句中使用赋值语句
'no-self-assign': 2, // 禁止自我赋值
'no-self-compare': 2, // 禁止自我比较
'no-unmodified-loop-condition': 2, // 禁止一成不变的循环条件
'no-useless-escape': 2, // 禁止不必要的转义字符
'no-class-assign': 2, // 禁止修改类声明的变量
'no-const-assign': 2, // 禁止修改const声明的常量
'no-dupe-class-members': 2, // 禁止类成员中出现重复的名称
'no-useless-computed-key': 2, // 禁止在对象中使用不必要的计算属性
'new-cap': [2, { newIsCap: true, capIsNew: false }], // 要求构造函数首字母大写
'new-parens': 2, // 要求构造无参构造函数时有圆括号
'no-whitespace-before-property': 2, // 禁止属性前有空白
'no-cond-assign': 2, // 禁止条件表达式中出现赋值操作符
'no-control-regex': 0, // 禁止在正则表达式中使用控制字符
'no-empty-character-class': 2, // 禁止在正则表达式中使用空字符集
'no-extra-boolean-cast': 2, // 禁止不必要的布尔转换
'no-func-assign': 2, // 禁止对function声明重新赋值
'no-inner-declarations': [2, 'functions'], // 禁止在嵌套块中出现变量声明或function声明
'no-obj-calls': 2, // 禁止把全局对象作为函数调用
'no-delete-var': 2, // 禁止删除变量
'no-shadow-restricted-names': 2, // 禁止将标识符定义为受限的名字
'no-dupe-args': 2, // 禁止function定义中出现重名参数
'for-direction': 2, // 强制"for"循环中更新子句的计算器朝着正确的方向移动
'no-unsafe-negation': 2, // 禁止对关系运算符的左操作数使用否定操作符
'comma-style': [2, 'last'], // 强制在逗号前后使用一致的空格
'operator-linebreak': [2, 'after', { overrides: { '?': 'before', ':': 'before' } }], // 强制操作符使用一致的换行符
'no-unexpected-multiline': 2, // 禁止出现令人困惑的多行表达式 结尾必须有分号
'no-multi-spaces': 2, // 禁止使用多个空格
'no-extra-parens': [2, 'functions'], // 禁止不必要的括号
'no-regex-spaces': 2, // 禁止正则表达式字面量中出现多个空格
'brace-style': [2, '1tbs', { allowSingleLine: true }], // 强制在代码块中使用一致的大括号风格
'arrow-spacing': [2, { before: true, after: true }], // "() => {};" // 强制箭头函数前后使用一致的空格
'template-curly-spacing': [2, 'never'], // 禁止模板字符串中嵌入表达式周围空格的使用 "`hello, ${ people.name }!`;"
'space-before-blocks': [2, 'always'], // 强制在块之前使用一致的空格 "function a() {}"
'space-infix-ops': 2, // 要求操作符周围有空格 "a ? b : c"
'space-unary-ops': [2, { words: true, nonwords: false }], // 强制在一元操作符前后使用一致的空格 "++foo;"
'spaced-comment': [1, 'always', { markers: ['global', 'globals', 'eslint', 'eslint-disable', '*package', '!', ','] }], // 强制在注释// 或/*使用一致的空格
'space-in-parens': [2, 'never'], // 强制在圆括号内使用一致的空格 "foo('bar');"
'array-bracket-spacing': [2, 'never'], // 禁止或强制在括号内使用空格 "var arr = ['foo', 'bar', 'baz'];"
'block-spacing': [2, 'always'], // 禁止或强制在代码块中开括号前和闭括号后有空格 "if (foo) { bar = 0; }"
'key-spacing': [2, { beforeColon: false, afterColon: true }] // 强制要求在对象字面量的属性中键和值之间使用一致的间距 "var obj = { "foo": 42 };"
}
};
效果如下图:
crrl + s
可以看到下面的效果
备注:
如果不好使,点开右下角的ESLint,看一下日志是不是哪里报错了
vue3.x + ts
按照vue2的配置运行:./node_modules/.bin/eslint --init
,区别如下:
1、
,选择是
2、
选择是
之后会默认创建一个.eslintrc.js
文件,但是默认配置存在些问题,可以替换成下面的
module.exports = {
root: true,
parser: 'vue-eslint-parser',
parserOptions: {
parser: '@typescript-eslint/parser',
sourceType: 'module',
ecmaFeatures: {
jsx: true,
tsx: true,
},
},
env: {
browser: true,
node: true,
},
plugins: ['@typescript-eslint'],
extends: ['plugin:vue/vue3-essential', 'plugin:@typescript-eslint/recommended'],
rules: {
// js/ts https://eslint.org/docs/rules
'no-console': process.env.NODE_ENV === 'production' ? 'off' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'eol-last': 'error',
'no-trailing-spaces': 'error',
'comma-style': ['error', 'last'],
'comma-dangle': ['error', 'always-multiline'],
quotes: ['error', 'single', { avoidEscape: true, allowTemplateLiterals: true }],
camelcase: 0,
semi: ['error', 'never'],
// indent: ['error', 4, { SwitchCase: 1 }],
'object-curly-spacing': ['error', 'always'],
'arrow-parens': ['error', 'as-needed'],
'quote-props': ['error', 'as-needed'],
'prefer-template': 'error',
'vue/no-v-html': 'off',
'vue/singleline-html-element-content-newline': 'off',
'vue/html-indent': ['error', 4],
'vue/require-default-prop': 'off',
'vue/require-explicit-emits': 'off',
'vue/multi-word-component-names': 'off',
'vue/one-component-per-file': 'off',
'vue/max-attributes-per-line': [
'error',
{
singleline: 5,
multiline: 1,
},
],
'vue/html-closing-bracket-spacing': 'error',
'vue/no-mutating-props': 'off',
'vue/v-on-event-hyphenation': 'off',
'vue/html-self-closing': [
'error',
{
html: {
void: 'always',
normal: 'always',
component: 'always',
},
svg: 'always',
math: 'always',
},
],
'@typescript-eslint/no-explicit-any': 'off', // any
'@typescript-eslint/explicit-module-boundary-types': 'off', // setup()
'@typescript-eslint/ban-types': 'off',
'@typescript-eslint/ban-ts-comment': 'off',
'@typescript-eslint/no-empty-function': 'off',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-var-requires': 0,
'@typescript-eslint/member-delimiter-style': [
'error',
{
multiline: {
delimiter: 'none',
requireLast: false,
},
singleline: {
delimiter: 'semi',
requireLast: false,
},
},
],
'@typescript-eslint/no-unused-vars': [
'error',
{
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
},
],
'no-unused-vars': [
'error',
{
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
},
],
},
ignorePatterns: [],
}
关于自定义规则,可以从上面选择一些比较用得到
效果
问题
最近发现eslint不好使了。
在这里也看不到eslint
的选项。原因:
看一下编辑器右下角有没有eslint
大部分原因应该就是eslint没有启用。解决:
1、文件 =》首选项 =》设置
2、在扩展里找到eslint
3、勾选上format:enable选项
4、这时候右下角应该就有eslint了,没有的话重启一下编辑器。
5、配置默认格式化
其他
对于旧项目可以在package.json
里添加如下命令
"lint:eslint": "eslint src/**/*.{vue,js,ts,tsx} --fix",