ESLint -- 要求对象字面量简写语法 (object-shorthand)

详细讲解请看object-shorthand

配置文件代码:

    // require method and property shorthand syntax for object literals
    // http://eslint.org/docs/rules/object-shorthand
    'object-shorthand': ['error', 'always', {
      ignoreConstructors: false, //constructor函数可以使用简写语法
      avoidQuotes: true, //字符串命名函数不能使用简写语法
    }],

Rule Details

该规则强制简写语法的使用。这适用于对象字面量中的所有方法(包括 generators )以及键名与已赋值的变量名相匹配的任何属性。

以下的每个属性都将发出警告:

/*eslint object-shorthand: "error"*/
/*eslint-env es6*/

var foo = {
    w: function() {},
    x: function *() {},
    [y]: function() {},
    z: z
};

这种情况下,期望的语法应该是这样:

/*eslint object-shorthand: "error"*/
/*eslint-env es6*/

var foo = {
    w() {},
    *x() {},
    [y]() {},
    z
};

该规则不标记对象字面量中的箭头函数。下面的示例将 不发出警告:

/*eslint object-shorthand: "error"*/
/*eslint-env es6*/

var foo = {
    x: (y) => y
};

Options

当设置为 "always"、"methods" 或 "properties",使用 "avoidQuotes" 简写语法可以忽略字符串字面量的键。这样做,在对象的键是字符串时,长格式的语法成为首选。注意:使用这个选项时,必须指定第一个参数。

{
    "object-shorthand": ["error", "always", { "avoidQuotes": true }]
}

选项 "avoidQuotes" 的 错误 代码示例:

/*eslint object-shorthand: ["error", "always", { "avoidQuotes": true }]*/
/*eslint-env es6*/

var foo = {
    "bar-baz"() {}
};

选项 "avoidQuotes" 的 正确 代码示例:

/*eslint object-shorthand: ["error", "always", { "avoidQuotes": true }]*/
/*eslint-env es6*/

var foo = {
    "bar-baz": function() {},
    "qux": qux
};

results matching ""

    No results matching ""