Javascript代码风格------Eslint,VS Code最佳实践

1.Creating Comments    创建注释

1.1 Use single-line syntax for single lines and multi-line syntax for multi-lines  单行使用单行注释,多行使用多行注释。

js支持两种注释:单行注释和多行注释。

单行注释:

// This is article about js coding format

多行注释:

/*
Using multiline comment syntax indicates clearly, from the start, that the following lines are part of a multiline comment.
Using the appropriate syntax also provides formatting that makes it easier for you and other developers to quickly see how long a multi-line comment is, 
where it starts, and where it ends.
*/

注释多行使用多行注释,相比使用单行注释去注释多行,使代码清晰,因为可以容易看出注释的起始位置。

VS Code 快捷键:

  • 单行注释 Ctrl + /     
  • 多行注释 Alt + Shift + A    

 注意和其它软件的快捷键冲突。

规则:multiline-comment-style

1.2 Multi-line syntax with leading asterisks for function   对于方法或者类注释使用带有前导*的多行注释

多行注释有两种:

"bare-block"
/*
    Disallows consecutive line comments in favor of block comments, 
    and disallows block comments from having a "*" character before each line.
*/

"starred-block"
/*
* (default): Disallows consecutive line comments in favor of block comments. 
* Additionally, requires block comments to have an aligned * character before each line.
*/
  • VS Code默认支持bare-block风格的多行注释,因此方便起见统一使用"bare-block"。

而对于方法,类以及文件的注释,VS Code也支持"starred-block"风格的,但是第一行是/**。直接在函数的前一行输入/**回车就会生成方法注释。

/**
 * 格式化数字:fixed ,再根据页面要求去零
 * @param {Number} num 百分比数字
 * @param {Number} len 长度
 */
function fixedRemoveZero(num, len) {
    //...
};

1.3 Include leading spaces in comments  注释包含前导空格

规则:spaced-comment, max-len

参考:.eslintrc.js

module.exports = {
  env: {
    es6: true
  },
  rules: {
    strict: ["error", "global"],
    "multiline-comment-style": ["error", "bare-block"],
    "spaced-comment": ["error", "always"]
  }
};
  • 如果一行的长度太长,可以在VS Code 中设置View -> toggle Word Wrap

2.Using Punctuation     使用标点符号

2.1 End statements with a semicolon    语句结尾使用分号

使用分号可以杜绝解析某些语句所产生歧义,方便阅读。

2.2 Don't rely on auto semicolon insertion  不要依赖解析器的自动分号插入

//没有分号断句下面的代码就会有歧义,到底是return了空,还是a+b
function abc(a,b){
    return             
        a + b
}

注意Object定义文本是以{}包围,但不是块作用域,因此也要用分号结尾。类似的还有函数表达式。

另外:语句与分号之间没有空格,没有多余的分号。 均使用eslint默认配置。

规则:semi,  semi-spacing,  no-extra-semi

//表达式中多余的换行,不仅会使代码难于阅读,也会产生歧义
userPrefs.setting = makeLowerCase
  (window.prompt('Urban or rural?'));

console.log(userPrefs
['setting']);

规则:no-unexpected-multiline

2.3 Standardize line length    规范代码每行的长度

规则:max-len

VS Code 设置:

  • File->Perferences->Settings
  • Search "ruler"
  • 打开settings.json,确认增加配置
"editor.wordWrap": "on",
"editor.rulers": [80],

2.4 Use commas consistently   一致的使用逗号

使用eslint默认:

"comma-style": ["error", "last"]

规则:comma-style

2.5 Include a comma in a list of values    在一数组(之后)加入逗号, 不建议

为了和Java,Json格式一致,不允许下列写法:

let foo = {
    bar: "baz",
    qux: "quux",    //多余的逗号
};

let arr = [1,2,];        //多余的逗号

const foo({
  bar: "baz",
  qux: "quux",            //多余的逗号
});

统一沿用,eslint的默认规则: 

"comma-dangle": ["error","never"]

规则: comma-dangle

参考.eslintrc.js

module.exports = {
  env: {
    es6: true
  },
  rules: {
    strict: ["error", "global"],
    "multiline-comment-style": ["error", "bare-block"],
    "spaced-comment": ["error", "always"],
    semi: ["error", "always"],
    "semi-spacing": "error",
    "no-extra-semi": "error",
    "no-unexpected-multiline": "error",
    "max-len": ["error", { "code": 80 }],
    "comma-style": ["error", "last"],
    "comma-dangle": ["error", "never"],
  },
};

3.Using spacing      使用空格

3.1 Indent consistently        缩进一致

consistently applied indents are key in being able to read the code and understand the relationship between statements.

一致的缩进是阅读代码和理解语句之间关系的关键所在。

VS Code 设置:

  • Editor: Tab Size  默认值:4.   项目可以依据实际需要设置成2
  • Editor : Detect Indentation    默认勾选。
  • Editor: Auto Indent   默认值:full
  • Editor: Format On Save    默认非勾选,依据个人喜好,建议勾选。
  • Editor: Format on Type    默认非勾选,依据个人喜好设定

3.2 Space before and after operators    操作符前后的空格

方便代码阅读且更容易高亮潜在的问题,例如:

let sum = i+++2;
//添加空格后:
let sum = i++ + 2;

规则:space-infix-ops

沿用默认值:

"space-infix-ops": ["error", { "int32Hint": false }]

VS Code 设置:

  • Javascript>Format 默认勾选。

3.3 Use a consistent format for blocks     对代码块使用一致的格式

VS Code 与 eslint默认都使用"One true brace style"的块书写风格

if (foo) {
  bar();
} else {
  baz();
}

规则:brace-stylespace-before-blocks

VS Code 设置:

  • Javascript>Format:Place Open Brace On New Line For Control Blocks     沿用默认值:不勾选
  • Javascript>Format:Place Open Brace On New Line For Functions            沿用默认值:不勾选

3.4 Include a space after keywords and arrows 在关键字和箭头之后包含一个空格

规则: keyword-spacing, arrow-spacing

默认值都是前后均有空格,沿用默认值

VS Code 设置:

  • javascript>Format:Insert Space After Function keywords For Anonymous Functions       沿用默认值:勾选
  • javascript>Format:Insert Space After Keywords In Control Flow Statements                   沿用默认值:勾选

3.5 Use consistent spaceing before function signature parentheses        函数签名括号前使用一致的空格

规则:space-before-function-paren

建议eslint配置:

"space-before-function-paren":["error",{
    "anonymous":"always",
    "named":"never",
    "asyncArrow":"always"
}],

VS Code 设置:

  •   Javascript>Format:Insert Space Before Function Parenthesis     默认值:非勾选,   建议勾选。

3.6 Break up and indent long-method chains        打断且缩进长的方法链式调用

规则:newline-per-chainsed-call

建议使用默认配置。

3.7 space consistently within enclosing characters        包围的字符串中空格一致

规则:space-in-parentsobject-curly-spacing

建议配置:

"space-in-parens":["error","never"],
"array-bracket-spacing":["error","never"],
"object-curly-spacing":["error","always"],

VS Code 设置:

  • Javascript>Format:Insert Space After Opening And Before Closing Jsx Expression Braces          默认值:check
  • Javascript>Format:Insert Space After Opening And Before Closing Nonempty Braces                  默认值:check
  • Javascript>Format:Insert Space After Opening And Before Closing Nonempty Bracket                 默认值:uncheck
  • Javascript>Format:Insert Space After Opening And Before Closing Nonempty Parenthesis          默认值:uncheck
  • Javascript>Format:Insert Space After Opening And Before Closing Template String Braces         默认值:uncheck, 建议check

提示:可以在.eslintignore 中定义将被eslint忽略的文件,例如:

!test.js                    //不忽略    test.js
.eslintrc.js                    //忽略eslintrc.js

3.8 Space after commas, but not before     逗号之后加空格,之前不要

规则: comma-spaceing

建议配置:

"comma-spacing": ["error", { "before": false, "after": true }],

VS Code 设置:

  • JavaScript › Format: Insert Space After Comma Delimiter        沿用默认值: 勾选

3.9 Limit Blank Space to One Line      限制无效的空行(不允许出现多空行)

规则: no-multiple-empty-lines

//代码段之间最多一个空行,文件结尾最多一个空行
"no-multiple-empty-lines": ["error", { "max": 1, "maxEOF": 1 }],

最终的.eslintrc.js参考

"use strict";

module.exports = {
  env: {
    es6: true,
  },
  rules: {
    strict: ["error", "global"],
    "multiline-comment-style": ["error", "bare-block"],
    "spaced-comment": ["error", "always"],
    semi: ["error", "always"],
    "semi-spacing": "error",
    "no-extra-semi": "error",
    "no-unexpected-multiline": "error",
    "max-len": ["error", { "code": 120 }],
    "comma-style": ["error", "last"],
    "comma-dangle": ["error", "always-multiline"],
    indent: ["error", 2],
    "space-infix-ops": "error",
    "space-before-blocks": "error",
    "brace-style": "error",
    "keyword-spacing": "error",
    "arrow-spacing": "error",
    "space-before-function-paren": [
      "error", { 
        "anonymous": "always", 
        "named": "never", 
        "asyncArrow": "always"
      },
    ],
    "newline-per-chained-call": "error",
    "space-in-parens": ["error", "never"],
    "array-bracket-spacing": ["error", "never"],
    "object-curly-spacing": ["error", "always"],
    "comma-spacing": ["error", { "before": false, "after": true }],
    "no-multiple-empty-lines": ["error", { "max": 1, "maxEOF": 1 }]
  }
};

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值