随着前端工程化的日益成熟,代码规范化对于开发效率的提高起着很大的做用,包括后期的维护,统一的规范能节省交接的时间成本,而规范包括目录结构、代码质量(命名、注释、JS规范、CSS规范、缩进等)javascript
一个插件化的 javascript 代码检测工具,它能够用于检查常见的 JavaScript 代码错误,也能够进行代码风格检查html
使用到两个扩展包(airbnb规范 & eslint-plugin-vue)前端
npm install -g eslint
复制代码
以上涉及到的rule规则在扩展包的基础上作了调整,基于两个规范作了修改适合你的规范规则git
方式2:手动建立.eslintrc.jsgithub
将方式1中的eslintconfig内容拷贝到.eslintrc.js文件中去vue-cli
方式3:用eslint 的命令行工具初始化后再修改.eslintrcnpm
"lint":"vue-cli-service lint"
复制代码
"lint":"eslint --ext .js,.vue src"
复制代码
🙆检测正确的提示 json
建立.eslintignore
集成到部署环节中的代码扫描环节,规范不经过则发布失败
在Jenkinsfile文件中加入
eslint官方 点我🚀
rules:{
"no-unused-vars": "warn", //是否支持存在未使用的变量
'no-debugger': process.env.NODE_ENV === 'production' ? 'error': 'off', //是否禁止debugger
'no-console': process.env.NODE_ENV === 'production' ? 'error': 'off', //是否禁止console.log
"no-var": "warn",
"no-eval": "warn",//禁止使用eval
}
复制代码
参考 Vue官方风格指南, 点我🚀
rules:{
"vue/prop-name-casing": ["error", "camelCase"],// prop名大小写:在声明 prop 的时候,其命名应该始终使用 camelCase
"vue/name-property-casing": ["error", "PascalCase"], // JS/JSX 中的组件名应该始终是 PascalCase 的
"vue/require-prop-types": "error", // props定义尽可能详细
"vue/require-v-for-key": "error", // v-for设置键值,与key结合使用
"vue/no-use-v-if-with-v-for": ["error", {
"allowUsingIterationVar": false
}], //不要把 v-if 和 v-for 用在同一个元素上
"vue/max-attributes-per-line": ["error", {
"singleline": 1,
"multiline": {
"max": 1,
"allowFirstLine": false
}
}], //多个特性的元素应该分多行撰写,每一个特性一行
}
复制代码
Prettier 是格式化代码工具。用来保持团队的项目风格统一
方式1 :根目录建立.prettierrc
方式2: package.json中新建prettier属性。
//方式1
module.exports = {
"printWidth": 160, //一行的字符数,若是超过会进行换行,默认为80
"tabWidth": 2, //一个tab表明几个空格数
"useTabs": false, //是否使用tab进行缩进,默认为false,表示用空格进行缩减
"singleQuote": false, //字符串是否使用单引号,默认为false,使用双引号
“useEditorConfig”: false, // 是否使用项目中的.editorconfig文件
"semi": true, //行位是否使用分号,默认为true
"bracketSpacing": true, //对象大括号直接是否有空格,默认为true,效果:{ foo: bar }
}
复制代码
使用eslint-plugin-prettier插件来添加prettier做为ESLint的规则配置,在ESLint运行Prettier
安装eslint-plugin-prettier
npm install --save-dev eslint-plugin-prettier
复制代码
// packjson
"eslintConfig": {
"extends": [
"plugin:vue/essential",
"@vue/airbnb",
"prettier"
],
"plugins": [
"prettier"
],
"rules": {
"prettier/prettier": "error",
}
}
复制代码
ps🏆: Prettier分别引入到extends与plugins中是为了防止eslint配置的rules与Prettier配置的rules冲突
文档类约束能够参考一些现有的团队规范
未完待续...