最近在搭建项目框架,想着上一个项目代码风格各异,就想着在新项目中引入Eslint来规范团队成员代码风格,保持统一,也方便你们维护代码,减小没必要要的错误。前端应用越发复杂,代码规范问题必须经过强制的方式保持统一。如下是团队逐渐摸索出的一些配置,各取所需。javascript
在用vue-cli3搭建项目的过程当中就会问你是否须要Eslint,选择就好来。若是没有选择后期又想加入eslint,能够手动安装Eslint的相关依赖。css
npm install eslint eslint-plugin-vue --save-dev
复制代码
须要注意:Node.js (>=6.14), npm version 3+。html
在项目根目录下新建一个文件,名.eslintrc.js。下面是我的的一些配置,能够自行参考。前端
module.exports = {
root: true,
env: {
browser: true,
node: true,
es6: true
},
extends: ["eslint:recommended", "plugin:vue/essential", "@vue/prettier"],
rules: {
"generator-star-spacing": "off",
"no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
"no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off",
"vue/no-parsing-error": [
2,
{
"unexpected-solidus-in-tag": false
}
]
},
parserOptions: {
parser: "babel-eslint",
ecmaVersion: 7,
sourceType: "module",
ecmaFeatures: {
// 添加ES特性支持,使之可以识别ES6语法
jsx: true
}
}
};
复制代码
若是一些文件不须要Eslint的校验,能够配置一个.eslintignore,里面写上须要排除的文件。vue
/build/
/config/
/dist/
/*.js
/test/unit/coverage/
复制代码
stylelint能够帮助咱们规范化css的书写,风格统一,减小错误。java
npm i -D stylelint stylelint-config-standard stylelint-webpack-plugin
复制代码
在项目根目录下新建配置文件.stylelintrc.js,相关配置以下:node
module.exports = {
extends: "stylelint-config-standard",
rules: {
"color-no-invalid-hex": true,
"rule-empty-line-before": null,
"color-hex-length": "long",
"color-hex-case": "lower",
"unit-whitelist": ["em", "rem", "%", "s", "px"],
"declaration-colon-newline-after": null
}
};
复制代码
虽然借助 Eslint 来提升代码质量,可是却没法保证代码风格统一。一个统一的代码风格对于团队来讲是颇有价值的,因此为了达到目的,咱们使用了 Prettier在保存和提交代码的时候,将代码修改为统一的风格。webpack
npm i -D prettier @vue/eslint-config-prettier
复制代码
相关配置写在.eslintrc.js中git
extends: ["eslint:recommended", "plugin:vue/essential", "@vue/prettier"]
复制代码
我使用的是vscode编辑器,同时配置了vscode。es6
{
"eslint.autoFixOnSave": true,
"eslint.validate": [
"javascript",
{
"language": "vue",
"autoFix": true
},
"html",
"vue"
],
"editor.wordWrap": "wordWrapColumn",
"editor.formatOnSave": true,
"vetur.validation.template": false,
"cSpell.ignoreWords": [
"menu",
"mixins"
]
}
复制代码
推荐使用vscode的同窗安装eslint和Prettier - Code formatter这两个插件,配合上面的配置,达到保存的时候自动格式化和校验的目的。
husky:一个方便用来处理 pre-commit 、 pre-push 等 githooks 的工具
lint-staged:对 git 暂存区的代码,运行 linters 的工具
npm i lint-staged husky -D
复制代码
...
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"src/**/*.{js,jsx,vue}": [
"prettier --tab-width 2 --write",
"vue-cli-service lint --fix",
"git add"
]
}
...
复制代码
这样就能够实如今提交的时候校验,保证错误的代码没法提交。
到目前为止,项目中就整合进了Eslint校验,prettier美化代码,提交hooks代码检查。