eslint在项目中使用
eslint 可以给我们的代码定义一些语法规范, 防止我们在语法上犯一些低级的错误, 格式上的问题, 团队协作时大家都使用统一的代码风格去书写, 让我们在看别人的代码时更方便.
在项目中安装依赖
1 2 3 4 5 6 7 8
| "eslint": "^5.8.0", "eslint-config-standard": "^12.0.0", "eslint-plugin-html": "^4.0.6", "eslint-plugin-import": "^2.14.0", "eslint-plugin-node": "^8.0.0", "eslint-plugin-promise": "^4.0.1", "eslint-plugin-react": "^7.11.1", "eslint-plugin-standard": "^4.0.0",
|
再添加一个.eslintrc 文件:
1 2 3 4 5 6
| { "extends": "standard", "plugins": [ "html", ], }
|
再在package.json文件中添加 eslint 校验命令
1
| "lint": "eslint --ext .js --ext .jsx --ext .vue src"
|
修复命令
1
| "lint-fix": "eslint --fix --ext .js --ext .jsx --ext .vue src"
|
校验时报错在运行 lint 命令时 jsx 文件报错: Parsing error: Unexpected token =
经过网上查找资料, 再安装一个 babel-eslint 依赖,安装后再在 .eslintrc 文件添加一行
1 2 3 4 5 6 7
| { "extends": "standard", "plugins": [ "html", ], "parse": "babel-eslint" }
|
一般我们使用webpack 和 babel 进行开发的时候我们都会指定他的 parse 为 babel-eslint, 因为 eslint 对有一些 es6 的语法不是很支持
我们还需要在 webpack 的 module 配置中最开始加上:
1 2 3 4 5 6
| { test: /\.(js|jsx|vue)$/, loader: 'eslint-loader', exclude: /node_modules/, enforce: 'pre' },
|
此时只是用命令对我们的代码进行检查, 下面是配置编辑器直接在写代码的时候立即提示出有语法问题的代码
git commit 钩子插件: husky
在正式的项目中, 我们会有团队协作, 我们可以在git commit 的对应 hook 进行 eslint 的检查, 首先要安装 husky:
注意: 在安装一些git hook 工具的时候, npm install 之前, 项目跟目录一定要是一个git 仓库, 这样对应的工具才能初始化成功, 不然会有问题,
然后配置 husky: 在package.json文件中添加:
1 2 3 4 5 6 7
| "husky": { "hooks": { "pre-commit": "npm run lint", "pre-push": "npm run lint", "commit-msg": "commitlint -E HUSKY_GIT_PARAMS" // 这一行需要配合 commitlint 插件使用 } }
|
配置好后每次 commit 的时候 eslint 都会去检测代码中的语法规范
git commit message插件: commitline
安装:
1 2 3 4 5 6 7 8
| // Install commitlint cli and conventional config npm install --save-dev @commitlint/{config-conventional,cli}
// For Windows: npm install --save-dev @commitlint/config-conventional @commitlint/cli
// Configure commitlint to use conventional config echo "module.exports = { extends: ['@commitlint/config-conventional'] }" > commitlint.config.js
|
默认使用angularjs 的规范
1 2 3 4 5 6 7 8 9 10 11 12 13
| // 规范: build:主要目的是修改项目构建系统(例如 glup,webpack,rollup 的配置等)的提交 ci:主要目的是修改项目继续集成流程(例如 Travis,Jenkins,GitLab CI,Circle等)的提交 docs:文档更新 feat:新增功能 merge:分支合并 Merge branch ? of ? fix:bug 修复 perf:性能, 体验优化 refactor:重构代码(既没有新增功能,也没有修复 bug) style:不影响程序逻辑的代码修改(修改空白字符,格式缩进,补全缺失的分号等,没有改变代码逻辑) test:新增测试用例或是更新现有测试 revert:回滚某个更早之前的提交 chore:不属于以上类型的其他类型
|