0%

代码规范

一、代码规范

工程没有具体统一的规范,包括有代码格式 , 命名规范 , 文档注释 。现在每个人都有自己的代码规范造成项目存在几种不同的规范,难以阅读。

统一代码规范不仅可以让程序员编写易于阅读、可维护性的代码,还有其他好处

  1. 规范的代码可以促进团队合作
  2. 规范的代码可以降低维护成本
  3. 规范的代码有助于 code review(代码审查)
  4. 养成代码规范的习惯,有助于程序员自身的成长

因此,我们就需要为我们的项目指定一套统一的代码规范。

二、如何制定代码规范

现在有很多优秀的开源代码规范,因此我们不需要从头开始制定一份代码规范,我们可以在优秀的代码规范上结合团队的需求作个性化修改。

下面列举一些比较出名的 JavaScript 代码规范:

CSS 代码规范也有不少,例如:

三、如何检查代码规范

  1. 使用工具校验代码格式。
  2. 利用code review审查变量命名、注释。

接来下我们来看一下如何使用工具校验代码格式

  1. 使用Eslint负责找出代码中的错误
  2. 使用Prettier负责代码格式化

3.1 Eslint配置

3.1.1 总览

基础

  1. eslint : lint代码的主要工具

解析器

  1. babel-eslint 该依赖包允许你使用一些实验特性的时候,依然能够用上Eslint语法检查。反过来说,当你代码并没有用到Eslint不支持的实验特性的时候是不需要安装此依赖包的。
  2. @typescript-eslint/parser Typescript语法的解析器,类似于babel-eslint解析器一样。对应parserOptions的配置参考官方的README。

扩展的配置

  1. eslint-config-airbnb 该包提供了所有的Airbnb的ESLint配置,作为一种扩展的共享配置,你是可以修改覆盖掉某些不需要的配置的,该工具包包含了react的相关Eslint规则(eslint-plugin-react与eslint-plugin-jsx-a11y),所以安装此依赖包的时候还需要安装刚才提及的两个插件
  2. eslint-config-airbnb-base 与上一个包的区别是,此依赖包不包含react的规则,一般用于服务端检查。
  3. eslint-config-prettier 将会禁用掉所有那些非必须或者和prettier冲突的规则。这让您可以使用您最喜欢的shareable配置,而不让它的风格选择在使用Prettier时碍事。请注意该配置只是将规则off掉,所以它只有在和别的配置一起使用的时候才有意义。

插件

  1. eslint-plugin-babel 和babel-eslint一起用的一款插件。babel-eslint在将eslint应用于Babel方面做得很好,但是它不能更改内置规则来支持实验性特性。eslint-plugin-babel重新实现了有问题的规则,因此就不会误报一些错误信息
  2. eslint-plugin-import该插件想要支持对ES2015+ (ES6+) import/export语法的校验, 并防止一些文件路径拼错或者是导入名称错误的情况
  3. eslint-plugin-jsx-a11y 该依赖包专注于检查JSX元素的可访问性。
  4. eslint-import-resolve-webpack 可以借助webpack的配置来辅助eslint解析,最有用的就是alias,从而避免unresolved的错误
  5. eslint-import-resolver-alias 解决我们在webpack中配置别名,但是eslint无法鉴别出来的问题,可以利用该插件进行额外的处理。
  6. eslint-plugin-react React专用的校验规则插件.
  7. eslint-plugin-react-hooks 利用该插件对hooks特性的代码作校验。
  8. eslint-plugin-prettier 该插件辅助Eslint可以平滑地与Prettier一起协作,并将Prettier的解析作为Eslint的一部分,在最后的输出可以给出修改意见。这样当Prettier格式化代码的时候,依然能够遵循我们的Eslint规则。如果你禁用掉了所有和代码格式化相关的Eslint规则的话,该插件可以更好得工作。所以你可以使用eslint-config-prettier禁用掉所有的格式化相关的规则(如果其他有效的Eslint规则与prettier在代码如何格式化的问题上不一致的时候,报错是在所难免的了)

3.1.2 配置

3.1.2.1 各属性


  1. env: 预定义那些环境需要用到的全局变量,可用的参数是:es6broswernode等。

    es6会使能所有的ECMAScript6的特性除了模块(这个功能在设置ecmaVersion版本为6的时候会自动设置)

    browser会添加所有的浏览器变量比如Windows

    node会添加所有的全局变量比如global

    更多环境配置参考Specifying Environments

  2. extends: 指定扩展的配置,配置支持递归扩展,支持规则的覆盖和聚合。

  3. plugins: 配置那些我们想要Linting规则的插件。

  4. parser: 默认ESlint使用Espree作为解析器,但是一旦我们使用babel的话,我们需要用babel-eslint。

  5. parserOptions: 当我们将默认的解析器从Espree改为babel-eslint的时候,我们需要指定parseOptions,这个是必须的。

    ecmaVersion: 默认值是5,可以设置为3、5、6、7、8、9、10,用来指定使用哪一个ECMAScript版本的语法。也可以设置基于年份的JS标准,比如2015(ECMA 6)

    sourceType: 如果你的代码是ECMAScript 模块写的,该字段配置为module,否则为script(默认值)

    ecmaFeatures:该对象指示你想使用的额外的语言特性

    1
    2
    3
    4
    5
    globalReturn:允许全局范围内的`return`语句

    impliedStrict:使能全局`strict`模式

    jsx:使能JSX
  6. rules: 自定义规则,可以覆盖掉extends的配置。

  7. settings:该字段定义的数据可以在所有的插件中共享。这样每条规则执行的时候都可以访问这里面定义的数据

更多配置选项参考官方文档Eslint


3.1.2.2 配置

  1. 在项目根目录新建.eslintrc.js文件
  2. 配置规则
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
module.exports = {
env: {
browser: true,
es2021: true,
node: true,
},
extends: ['airbnb', 'airbnb/hooks'],
ignorePatterns: ['node_modules/', 'ucf-publish/', 'ucf.config.js', 'ucf-common/static/'],
parser: '@babel/eslint-parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 12,
allowImportExportEverywhere: false,
sourceType: 'module',
requireConfigFile: false,
babelOptions: {
presets: ['@babel/preset-react'],
},
},
// 0 不启用 1 警告 2 禁用
rules: {
// 特殊rules配置
'import/no-extraneous-dependencies': [
0,
{
devDependencies: false,
optionalDependencies: false,
peerDependencies: false,
packageDir: './',
},
],
'react/jsx-filename-extension': 0,
'import/extensions': 'off',
'no-debugger': 2, // 禁止使用debugger
},
settings: {
'import/resolver': {
node: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
paths: ['./ucf-common'],
},
alias: {
map: [
['components', './ucf-common/src/components/'], // 别名路径
['utils', './ucf-common/src/utils/'], // 别名路径
['static', './ucf-common/src/static/'], // 别名路径
['styles', './ucf-common/src/styles/'], // 别名路径
],
},
},
},
};

  1. 检测项目存在的问题

    1. 使用 npm eslint '指定文件' 检测某一文件
  2. 修正代码中的格式问题

    1. 使用npx eslint xxx.js --fix来修正代码中的部分格式问题
  3. 可以通过使用 VSCode插件来在代码中给出代码错误提示。

    1. 下载插件Eslint

      image-20220417163546554

      1. 在settings.json中进行配置

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        "eslint.alwaysShowStatus": true,
        "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true,
        },
        "eslint.options": {
        "parser": "@babel/eslint-parser"
        },
        "eslint.validate": [
        "javascript",
        "javascriptreact",
        "html",
        "react"
        ],
      2. 验证Eslint校验是否开启

        可以通过vscode右下角的Eslint判断我们所配置的是否生效了。

        image-20220417164911943

3.2 Prettier配置

将Prettier集成在Eslint中,Eslint的配置可能会和Prettier的配置相冲突,因此我们可以通过eslint-config-prettier来关闭冲突规则。

3.2.1 总览

  1. prettier 原始实现版本,定义了prettier规则并实现这些规则。
  2. eslint-config-prettier 关闭eslint中与prettier相互冲突的规则。
  3. eslint-plugin-prettier 赋予eslintprettier格式化代码的能力。

最基础的是prettier,然后你需要用eslint-config-prettier去禁用掉所有和prettier冲突的规则,这样才可以使用eslint-plugin-prettier去以符合eslint规则的方式格式化代码并提示对应的修改建议。

3.2.2 配置

  1. 修改.eslintrc.js文件
1
2
- extends: ['airbnb', 'airbnb/hooks']
+ extends: ['airbnb', 'airbnb/hooks', 'plugin:prettier/recommended']

规则plugin:prettier/recommended 做了什么?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// node_modules/eslint-plugin-prettier/eslint-plugin-prettier.js
module.exports = {
// plugin:prettier/recommended 就是加载这个
configs: {
recommended: {
extends: ['prettier'],
plugins: ['prettier'],
rules: {
'prettier/prettier': 'error',
'arrow-body-style': 'off',
'prefer-arrow-callback': 'off',
},
},
},
// 其他的
}
  1. 在项目根目录新建.prettierrc.js文件
  2. 配置规则
1
2
3
4
5
6
7
8
9
10
module.exports = {
printWidth: 120,
tabWidth: 4,
semi: true,
singleQuote: true,
useTabs: false,
trailingComma: 'es5',
endOfLine: 'auto',
};

  1. 格式化代码

    1. 格式化全部文档

      1
      2
      3
      npx prettier --write .
      //或
      yarn prettier --write .
    2. 格式化指定文档

      1
      2
      3
      npx prettier --write src/components/Button.js
      //或
      yarn prettier --write src/components/Button.js
  2. 检查文档是否已格式化

    1
    2
    3
    4
    npx prettier --check .
    //或
    yarn prettier --check .
    //检查指定文件同上
  3. 同样的,我们安装vscode中的Prettier,这样就可以运用编辑器快捷键进行格式化。

    image-20220417170410876

  4. .setting.json文件中配置

    1
    2
    3
    "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
    },

3.3 检查CSS规范

3.3.1 总览

  1. stylelint 运行工具
  2. stylelint-config-standard 是stylelint的推荐配置
  3. stylelint-order是用来在格式化css文件时对代码的属性进行排序。
  4. stylelint-config-css-modulescss-module的方案来处理样式文件

3.3.2 配置

  1. 在项目根目录新建.stylelintrc.js 文件
  2. 配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// .stylelintrc.js
module.exports = {
processors: [],
plugins: ['stylelint-order'],
extends: ['stylelint-config-standard', 'stylelint-config-css-modules'],
rules: {
'string-quotes': 'single', // 单引号
'at-rule-empty-line-before': null,
'at-rule-no-unknown': null,
'at-rule-name-case': 'lower', // 指定@规则名的大小写
'length-zero-no-unit': true, // 禁止零长度的单位(可自动修复)
'shorthand-property-no-redundant-values': true, // 简写属性
'number-leading-zero': 'never', // 小数不带0
'declaration-block-no-duplicate-properties': true, // 禁止声明快重复属性
'no-descending-specificity': true, // 禁止在具有较高优先级的选择器后出现被其覆盖的较低优先级的选择器。
'selector-max-id': 0, // 限制一个选择器中 ID 选择器的数量
'max-nesting-depth': 3,
indentation: [
2,
{
// 指定缩进 warning 提醒
severity: 'warning',
},
],
'order/properties-order': [
// 规则顺序
'position',
'top',
'right',
'bottom',
'left',
'z-index',
'display',
'float',
'width',
'height',
'max-width',
'max-height',
'min-width',
'min-height',
'padding',
'padding-top',
'padding-right',
'padding-bottom',
'padding-left',
'margin',
'margin-top',
'margin-right',
'margin-bottom',
'margin-left',
'margin-collapse',
'margin-top-collapse',
'margin-right-collapse',
'margin-bottom-collapse',
'margin-left-collapse',
'overflow',
'overflow-x',
'overflow-y',
'clip',
'clear',
'font',
'font-family',
'font-size',
'font-smoothing',
'osx-font-smoothing',
'font-style',
'font-weight',
'line-height',
'letter-spacing',
'word-spacing',
'color',
'text-align',
'text-decoration',
'text-indent',
'text-overflow',
'text-rendering',
'text-size-adjust',
'text-shadow',
'text-transform',
'word-break',
'word-wrap',
'white-space',
'vertical-align',
'list-style',
'list-style-type',
'list-style-position',
'list-style-image',
'pointer-events',
'cursor',
'background',
'background-color',
'border',
'border-radius',
'content',
'outline',
'outline-offset',
'opacity',
'filter',
'visibility',
'size',
'transform',
],
},
};

  1. 安装vscode-stylelint插件,实现保存时自动autoSave

    1. image-20220418090151929

    2. Stylelinestylelint-plus的区别是,stylelint-plus支持了保存时autoSave

    3. 配置vscode-setting.json文件

      参考

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      "stylelint.validate": [
      "css",
      "less",
      "postcss",
      "scss",
      "vue",
      "sass"
      ],
      "editor.codeActionsOnSave": {
      "source.fixAll.stylelint": true
      },
    4. 忽略lint文件

      项目中有一些不需要格式化的代码,我们可以配置在运行lint时忽略这些文件

      有三种方法可以起到忽略作用

      1. 我们可以在.stylelintrc.js中配置ignoreFiles
      2. 创建.stylelintignore文件。
      3. 我们可以通过 /* stylelint-disable */的方法,来对代码块进行忽略lint检测。

      这里我采用的是第二种方式

      1. 新建.stylelintignore 文件

      2. 配置

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        *.js
        *.tsx
        *.ts
        *.json
        *.png
        *.eot
        *.ttf
        *.woff
        *.css
        src/styles/antd-overrides.less

参考

  1. 最全的Eslint配置模板,从此统一团队的编程习惯
  2. eslint或stylelint配置完之后vscode无法自动格式化问题的解决办法
  3. stylelint 接入实战踩坑总结
  4. 带你入门前端工程