项目质量监测(二)03-Lint工具之ESLint——ESLint使用方法 & 常用ESlint配置 & 安装模块cross-env配置环境变量
ESLint的使用方法
-
本地使用方法:
如果你想让 ESLint 成为你项目构建系统的一部分,我们建议在本地安装。你可以使用 npm:
$ npm install eslint --save-dev
紧接着你应该设置一个配置文件:
$ ./node_modules/.bin/eslint --init
之后,你可以在你项目根目录运行 ESLint:
$ ./node_modules/.bin/eslint yourfile.js
使用本地安装的 ESLint 时,你使用的任何插件或可分享的配置也都必须在本地安装。
-
全局使用
如果你想使 ESLint 适用于你所有的项目,我们建议你全局安装 ESLint。你可以使用 npm:
$ npm install -g eslint
紧接着你应该设置一个配置文件:
$ eslint --init
之后,你可以在任何文件或目录运行 ESLint:
$ eslint yourfile.js //文件名,通常在根目录运行
常用ESlint配置
ESLint的规范:
Standard: https://github.com/standard/eslint-config-standard
具体地址:eslintrc.json
Airbnb: https://github.com/airbnb/javascript
使用规则-rules:https://cn.eslint.org/docs/rules/comma-dangle
-
comma拖尾逗号
rules: { "comma-dangle": ["error", "never"], }
Bad:
var foo = { a: '123', b: '321', // wrong error }
Right:
var foo = { a: '123', b: '321' }
-
quotes引号
rules: { "quotes":["error","single"] //单引号 }
-
semi分号
rules: { "semi":["error","never"] //句尾不用分号 }
-
空行
rules: { //中间最多2空行或1空行,末尾1空行或0空行 "no-multiple-empty-lines": ["error", { "max": 2, "maxEOF": 1 }] }
-
驼峰命名
rules: { "camelcase":"error" //驼峰命名-第二个词首字母大写 }
-
日志输出
rules: { //"no-console":"error", //不打印 //正式环境不允许使用console,测试环境可以 "no-console":process.env.NODE_ENV ==='production'?"error":"off", "no-debugger":"error", //不调试--同上 "no-debugger":process.env.NODE_ENV ==='production'?"error":"off", }
补充:
验证
"no-console":process.env.NODE_ENV ==='production'?"error":"off",
cross-env配置环境变量
操作步骤:
cross-env包:用于配置环境变量
https://www.npmjs.com/package/cross-env
安装:
npm install cross-env -D
在package.json中进行配置
示例:
{ "scripts": { "build": "cross-env FIRST_ENV=one SECOND_ENV=two node ./my-program" } }
实例
1
"scripts": { // "test": "echo \"Error: no test specified\" && exit 1" "lint": "cross-env NODE_ENV=production eslint app.js", "lint:creat":"eslint --init" },
2、执行
npm run lint
3、eslint改node
"scripts": {
"lint": "cross-env NODE_ENV=production node app.js",
"lint:creat":"eslint --init"
},
4、执行npm run lint
1-验证打印
2-打印
-
强等判断 ===
rules: { "eqeqeq":"error" //取值——error或off }
-
冗余的变量
rules: { "no-unused-vars":"error" //取值——error或off }
-
空格
-
关键字后的空格
-
函数名后的空格
rules: { "space-before-blocks":"error", //强制空格 function a (){} }
-
缩进
rules: { "indent":["error",2], //缩进2格 }
-