美文网首页
ESLint在Vue中的使用

ESLint在Vue中的使用

作者: pansly | 来源:发表于2019-02-24 22:06 被阅读0次

ESLint的用途

1、审查代码是否符合编码规范和统一的代码风格;
2、审查代码是否存在语法错误; 中文网地址 http://eslint.cn/
3、验证规则是写在 .eslintrc 文件中的 rules 下面的,配置一条验证规则,这么写规则名,值可以是以下几种:
1)、off 或 0:表示不验证规则。
2)、warn 或 1:表示验证规则,当不满足时,给警告。
3)、error 或 2 :表示验证规则,不满足时报错。
4)、如果规则有参数,则这么写
5)、规则名: [值, 参数1, 参数2...] 如"indent": ["error", 2]

1、Airbnb 前端编码规范

遵循编码规范和使用语法检测,可以很好的提高代码的可读性,可维护性,并有效的减少一些编码错误,这里学习的是著名的独角兽公司Airbnb的前端编码规范,Airbnb编码规范多数都可以配置成ESLint的规则从而在编译时进行语法检查。

1)对所有的引用使用 const ,不要使用 var。 eslint: prefer-const

  1. 如果一定需要可变动的引用,使用 let 代替 var。 eslint: no-var
  2. 使用字面值创建对象。 eslint: no-new-object

// bad

const item = new Object();

// good

const item = {};

(4)使用对象方法的简写 eslint: object-shorthand

// bad

 const atom = { 
    value: 1, 
    addValue: function (value) {      
          return atom.value + value;      
   },
 };

// good

 const atom = {
      value: 1,     
     addValue(value) {
         return atom.value + value;
     },
};

使用对象属性值的简写 eslint: object-shorthand

 const lukeSkywalker = 'Luke Skywalker';

// bad

const obj = {
   lukeSkywalker: lukeSkywalker,
};

// good

 const obj = {
    lukeSkywalker,
 };

5)只有对无效的标识符的属性才使用引号. eslint: quote-props

// bad

 const bad = {
  'foo': 3,  
   'bar': 4,
   'data-blah': 5,
 };

// good

 const good = {
  foo: 3,
  bar: 4,
   'data-blah': 5,
 };

6)不要直接调用 Object.prototype 的方法,如:hasOwnProperty, propertyIsEnumerable, 和 isPrototypeOf

// bad

 console.log(object.hasOwnProperty(key));

// good

 console.log(Object.prototype.hasOwnProperty.call(object, key));

// best

 const has = Object.prototype.hasOwnProperty;  // cache the lookup once, in module scope.

/* or */

const has = require('has');
console.log(has.call(object, key));

7)浅拷贝对象的时候最好是使用 … 操作符而不是 Object.assign

//very bad

const original = { a: 1, b: 2 };
const copy = Object.assign(original, { c: 3 }); // this mutates `original`
delete copy.a; // so does this

// bad

const original = { a: 1, b: 2 };
const copy = Object.assign({}, original, { c: 3 }); // copy = { a: 1, b: 2, c: 3 }

// good

const original = { a: 1, b: 2 };
 const copy = { ...original, c: 3 }; // copy = { a: 1, b: 2, c: 3 }
 const { a, ...noA } = copy; // noA = { b: 2, c: 3 }

8)使用字面值创建数组 eslint: no-array-constructor

// good

 const items = [];

// bad

 const items = new Array();

9)在数组方法回调中使用return语句。如果函数体包含一个单独的语句,返回一个没有副作用的表达式,那么省略返回是可以的。 eslint: array-callback-return

// bad

 inbox.filter((msg) = {
   const { subject, author } = msg;
   if (subject === 'Mockingbird') {
     return author === 'Harper Lee';
   } else {
     return false;  
  }
 });

// good

 inbox.filter((msg) = {  
   const { subject, author } = msg;
   if (subject === 'Mockingbird') {
      return author === 'Harper Lee';
   }
   return false;
 });

10)如果数组有多行,则在打开位置使用换行符,然后在关闭数组括号之前使用换行符。

// bad

 const arr = [
    [0, 1], [2, 3], [4, 5]
 ];
 const objectInArray = [{
   id: 1
 }, {
  id: 2
 }];
 const numberInArray = [ 1, 2 ];

// good

 const arr = [[0, 1], [2, 3], [4, 5]];
 const objectInArray = [{id: 1},{id: 2}];
 const numberInArray = [ 1, 2];

11)在访问和使用对象的多个属性时,使用对象的解构,解构能减少临时引用属性。 eslint: prefer-destructuring

// bad

 function getFullName(user) {
   const firstName = user.firstName;
   const lastName = user.lastName; 
   return `${firstName} ${lastName}`;
 }

// good

 function getFullName(user) {
    const { firstName, lastName } = user;
    return `${firstName} ${lastName}`;
 }

// best

 function getFullName({ firstName, lastName }) {
   return `${firstName} ${lastName}`;
 }

12)使用数组解构. eslint: prefer-destructuring

 const arr = [1, 2, 3, 4];

// bad

 const first = arr[0];
 const second = arr[1];

// good

 const [first, second] = arr;

13)字符串使用单引号''。 eslint: quotes

// bad
 const name = "Capt. Janeway";

// bad - 模板字面量应该包含插值或换行符

 const name = `Capt. Janeway`;

// good

 const name = 'Capt. Janeway';

14)以编程方式构建字符串时, 使用模板字符串代替字符串连接. eslint: prefer-templatetemplate-curly-spacing

// bad

 function sayHi(name) {
     return 'How are you, ' + name + '?'
 }

// good

 function sayHi(name) {
    return `How are you, ${name}?`;
 }

15)永远不要对字符串使用eval(),他产生无数的漏洞。 eslint: no-eval

16)不要对字符串使用不必要的转义字符. eslint: no-useless-escape 为什么? 反斜杠损害可读性,因此他们只要在必须的时候使用

// bad

 const foo = '\'this\' \i\s \"quoted\"';

// good

 const foo = '\'this\' is "quoted"';
 const foo = `my name is '${name}'`;

17)使用命名函数表达式而不是函数声明。eslint: func-style

// bad

 function foo() {
        // ...
     }

// bad

 const foo = function () {
         // ...
     };

// good
// 用明显区别于变量引用调用的词汇命名

 const short = function longUniqueMoreDescriptiveLexicalFoo() {
        // ...
     };

18)永远不要在一个非函数代码块中声明一个函数(if,while等等),把这个函数赋值给一个变量代替. 浏览器允许你这么做,但是他们 的解析各不相同。. eslint: no-loop-func

// 千万不要这样做!
// 有的浏览器会把foo声明为返回first的那个函数
// 而有的浏览器则会让foo返回second

 if (true) {
    function foo() {
        return 'first';
    }
  }  else {
    function foo() {
        return 'second';
    }
 }
 foo();

// 记住,这种情况下要使用函数表达式:

 let foo;
       if (true) {
         foo = function() {
           return 'first';
         };
      } else {
        foo = function() {
           return 'second';
        };
      }
     foo();

19)永远不要命名一个参数为 arguments。这将会覆盖原来函数作用域内的 arguments 对象

// bad

 function foo(name, options, arguments) {
     // ...
  }

// good

 function foo(name, options, args) {
     // ...
  }

20) 使用默认的传参而不是改变函数的参数。
// really bad

 function handleThings(opts) {
         // 不!我们不应该改变函数的参数No!
         // 更坏的是如果opts是false,他将被设置为一个对象
         // 这可能是你想要的,但它可以引起一些小的bug
           opts = opts || {};
        // ...
     }

// still bad

 function handleThings(opts) {
        if (opts === void 0) {
            opts = {};
        }
        // ...
    }

// good

 function handleThings(opts = {}) {
        // ...
     }

21)当您必须使用匿名函数(如在传递一个内联回调时),请使用箭头函数表示法。 eslint: prefer-arrow-callback
// bad

 [1, 2, 3].map(function (x) {
        const y = x + 1;
        return x * y 
     });

// good

 [1, 2, 3].map((x) = {        
         const y = x + 1;       
         return x * y;
     });

2、什么是ESlint?

ESLint 是用来检查我们写的 JavaScript代码是否满足指定规则的静态代码检查工具。

3、在 webpack 中使用 ESlint:

1)安装 ESLint 的依赖。

npm install --save-dev eslint eslint-loader

2)新建名为 .eslintrc 的文件。该文件的内容为对 ESLint 的配置。内容类似如下

 { 
     "extends": "airbnb", //启用规则
     "plugins": [
         "html",
         "standard",    
         "promise"
    ],    //EsLint允许使用第三方插件
   "parser": "babel-eslint",//EsLint默认使用esprima做脚本解析,当然你也切换他,比如切换成babel-eslint解析
    "parserOptions": {
     "ecmaVersion": 6,
     "sourceType": "module",
     "ecmaFeatures": {
           "experimentalObjectRestSpread": true,
           "jsx": true,
           "globalReturn": true
     }
   },
   "env": {
     "es6": true,
     "browser": true,    
     "node": true,
     "jquery": true,
     "mocha": true
   },
   "rules": {
     "indent": ["error", 2], // 代码缩进
     "no-param-reassign": ["error", {"props": false}], //禁止对 function 的参数进行重新赋值      "no-undef": 0,                //禁用未声明的变量
     "no-console": 0,                //禁止使用console
     "no-debugger": 1,              //禁止使用debugger  
     "import/extensions": 0,    //取消对文件扩展名的验证
     "import/no-unresolved": 0,  //取消自动解析路径,以此开启alias的别名路径设置 
     "import/no-named-as-default": 0,    //使用导出名称作为默认导出标识符的报告
     "import/first": 0,                  //带变量名的必须放在头部
     "no-var": 1,                        //禁用var,用let和const代替
     "no-unused-expressions": 0,    //禁止无用的表达式
     "semi": [1, "always"],      //语句强制分号结尾
     "no-trailing-spaces": 0,        //一行结束后面不要有空格
     "eol-last": 0,                  //文件以单一的换行符结束
     "no-restricted-syntax": 0,      //禁用特定的语法
     "max-len": [0, 80, 4],          //字符串最大长度
     "no-plusplus": 0,              //禁止使用++,--
     "consistent-return": 0,    //return 后面是否允许省略    
     "no-tabs": "off",       //此规则在文件内的任何位置查找制表符:代码,注释或其他任何
 内容
     "eqeqeq": 0,                        //比较用 === 或 !==
     "import/no-named-as-default-member": 0,
     "prefer-destructuring": ["error", {"object": false, "array": false}],//此规则强制使用解构而不是通过成员表达式访问属性。   
  "no-underscore-dangle": 0,  //标识符不能以_开头或结尾
  "no-restricted-properties": [2,{"object": "require","message": "Please call require() directly."
   } ],
     "no-alert": 0,                  //禁止使用alert
     "global-require": 0,        //此规则要求所有调用require()都位于模块的顶层
     "no-lone-blocks": 0,          //禁止不必要的嵌套块
     "no-unused-vars": ["error", {
        "vars": "all",        
        "args": "none"
       }   
      ]                            //不能有声明后未被使用的变量或参数
   },
   "globals": {},                //指定你所要使用的全局变量
   "settings": {}  
 }

env 指定代码运行的环境。 parserOptions 指定 JavaScript 相关的选项。ecmaVersion 指定用哪个 ECMAScript 的版本,默认是 3 和 5。 rules 指定具体检查的规则。

相关文章

网友评论

      本文标题:ESLint在Vue中的使用

      本文链接:https://www.haomeiwen.com/subject/tihiyqtx.html