eslint prettier 初入门

# eslint prettier 初入门

它们是用来做代码格式化的。

eslint 不仅作代码规范,还有检查变量声明了是否调用,是否有console.log语句等。

全局安装eslintnpm i eslint -g(如果之前全局安装过了就不用了),再npx eslint --init

eslint index.js --fix

# 既然有vscode插件,那么还装eslintnpm包吗?

要装。虽然vscode插件也可以单独配置格式,但是如果项目中有.eslintrc.js文件,那么eslint插件会优先执行.eslintrc.js文件的配置。

并且不是每个人都会装eslintvscode插件。此时eslintnpm包就作为一个保障,并且里面的.eslintrc.js配置就作为标准配置。

vscode插件只是为了方便自己开发而已。

# prettiernpm

下载prettier npm i prettier -D,然后执行npx prettier --write index.js npx prettier --write index.css,我们可以发现刚才不工整的代码,全部都变得工工整整了。

# 代码规范

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

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

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

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

# 如何制定代码规范

一些比较出名的 JavaScript 代码规范:

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

# 如何检查代码规范

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

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

  1. 使用 Eslint 负责找出代码中的错误
  2. 使用 Prettier 负责代码格式化
  3. 使用 stylelint 负责检查CSS代码规范

# Eslint配置

基础

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

解析器

  1. babel-eslint 该依赖包允许你使用一些实验特性的时候
  2. @typescript-eslint/parser Typescript语法的解析器,类似于babel-eslint解析器一样。对应parserOptions的配置参考官方的README

扩展的配置

  1. eslint-config-airbnb 该包提供了所有的AirbnbESLint配置,作为一种扩展的共享配置, 你是可以修改覆盖掉某些不需要配置的,该工具包包含了react的相关Eslint规则(eslint-plugin-reacteslint-plugin-jsx-a11y), 所以安装此依赖包的时候还需要安装刚才提及的两个插件
  2. eslint-config-airbnb-base 与上一个包的区别是,此依赖包不包含react的规则,一般用于服务端检查。
  3. eslint-config-prettier 将会禁用掉所有那些非必须或者和 prettier 冲突的规则。

插件

  1. eslint-plugin-babel 和babel-eslint一起用的一款插件。babel-eslint在将eslint应用于Babel方面做得很好, 但是它不能更改内置规则来支持实验性特性。eslint-plugin-babel重新实现了有问题的规则,因此就不会误报一些错误信息
  2. eslint-plugin-import该插件想要支持对ES2015+ (ES6+) import/export语法的校验, 并防止一些文件路径拼错或者是导入名称错误的情况
  3. eslint-import-resolve-webpack 可以借助webpack的配置来辅助eslint解析,最有用的就是alias,从而避免unresolved的错误
  4. eslint-plugin-jsx-a11y 该依赖包专注于检查JSX元素的可访问性。
  5. eslint-import-resolver-alias 解决我们在webpack中配置别名,但是eslint无法鉴别出来的问题,可以利用该插件进行额外的处理。
  6. eslint-plugin-react React专用的校验规则插件.
  7. eslint-plugin-react-hooks 利用该插件对hooks特性的代码作校验。

配置

  1. env: 预定义那些环境需要用到的全局变量,可用的参数是:es6、broswer、node等。
  • es6会使能所有的ECMAScript6的特性除了模块(这个功能在设置ecmaVersion版本为6的时候会自动设置)
  • browser会添加所有的浏览器变量比如Windows
  • node会添加所有的全局变量比如global
  1. extends: 指定扩展的配置,配置支持递归扩展,支持规则的覆盖和聚合。

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

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

  4. 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. rules: 自定义规则,可以覆盖掉extends的配置。

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

.eslintrc.js文件

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
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

检测项目存在的问题

使用 npm eslint '指定文件' 检测某一文件

修正代码中的格式问题

使用 npx eslint xxx.js --fix 来修正代码中的部分格式问题

# Prettier配置

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

# 检查css规范

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

.stylelintrc.js

// .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
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

# 代码规范

代码规范、目录命名规范、图片命名规范、Vue 组件规范、React 组件规范 等

上次更新: 2022/6/27 上午9:19:22