项目规范化标准介绍及相关实践

规范化标准介绍:

规范化是我们践行前端工程化中重要的一部分,本文将会从以下几个方面展开介绍。

  • 首先为什需要有规范化
    • 软件开发往往需要多人协同
    • 不同开发者有不同的编码习惯和喜好
    • 不同的喜好容易增加项目维护成本
    • 每个项目或团队需要明确统一的标准
  • 哪里需要规范化标准
    • 代码、文档、甚至是提交日志
    • 开发过程中人为编写的成果都需要规范化
    • 代码的标准化规范最为重要,它决定了项目的质量和可维护性
      •  统一关键词、操作符间的空格
      •  统一代码的缩进方式
      •  统一是否使用分号结尾
      •  统一变量或函数的命名规范等
  •     实施规范化的方法

        1、没有工具化协助之前,需要编写前人为的标准约定,以方便开发过程中成员间code review按约定标准进行检查。
        2、通过工具实现Lint 保障提交前的代码风格统一。
            Lint就是通过工具找到项目中不合规范的地方的过程。编译之前就检查出这些问题,以避免编译之后带来不必要的问题。
 

常见的规范化实现方式

ESLint工具的使用:

        ESLint是目前最为主流到的JavaScript Lint工具,可用于监测JS代码质量。使用ESLint很容易统一开发者的编码风格,发现代码编写时的一些潜在问题,同时也可以帮助开发者提升编码能力。

ESLint的安装步骤
    1、初始化项目:

$ npm init


    2、安装ESLint模块开发依赖

$ npm i eslint -D


    3、通过CLI命令校验安装结果
 

$ node_modules/.bin/eslint -v
v8.17.0

$ npx eslint -v
v8.17.0

安装后可以在我们的node_modules/.bin目录下找到我们eslint命令,或者使用npx命令也可以直接使用我们安装到node_modules下的包来运行,不用使用完整的文件路径。
 

快速上手ESLint

ESLint检查步骤
    1、编写’问题‘代码

// index.js
const foo = 123



function fn() {
    console.log('hello');

        console.log('eslint in using');


}

fn(

syy()



    2、使用eslint执行检查测

$ npx eslint ./index.js

Oops! Something went wrong! :(

ESLint: 8.17.0

ESLint couldn't find the config "xo" to extend from. Please check that the name of the config is correct.

这里提示我们没有找到eslint的相关配置文件,所以它不知道怎么检测该怎么进行,有那些规则需要检测。所以我们需要给它配置一个config文件。


    3、完成eslint使用配置

$ npx eslint --init                   
You can also run this command directly using 'npm init @eslint/config'.
npx: 40 安装成功,用时 3.245 秒
✔ How would you like to use ESLint? · style
✔ What type of modules does your project use? · none
✔ Which framework does your project use? · none
✔ Does your project use TypeScript? · No / Yes
✔ Where does your code run? · browser
✔ How would you like to define a style for your project? · guide
✔ Which style guide do you want to follow? · standard
✔ What format do you want your config file to be in? · JavaScript
Checking peerDependencies of eslint-config-standard@latest
The config that you've selected requires the following dependencies:

eslint-config-standard@latest eslint@^8.0.1 eslint-plugin-import@^2.25.2 eslint-plugin-n@^15.0.0 eslint-plugin-promise@^6.0.0
✔ Would you like to install them now? · No / Yes
✔ Which package manager do you want to use? · pnpm
Installing eslint-config-standard@latest, eslint@^8.0.1, eslint-plugin-import@^2.25.2, eslint-plugin-n@^15.0.0, eslint-plugin-promise@^6.0.0
Could not execute pnpm. Please install the following packages with a package manager of your choice: eslint-config-standard@latest, eslint@^8.0.1, eslint-plugin-import@^2.25.2, eslint-plugin-n@^15.0.0, eslint-plugin-promise@^6.0.0
A config file was generated, but the config file itself may not follow your linting rules.
Successfully created .eslintrc.js file in /Users/huiquandeng/projects/lg-fed-lp/my-module/eslintusage

        经过上面的一轮cli的预设问题的回答,eslint就为我们初始化并创建了一个名为:.eslintrc.js的配置文件,并根据我们的问题回答安装了一些必要的开发依赖包。

其中的配置内容格式如下:
 

module.exports = {
    "root": true,
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": [
        "standard"
    ],
    "parserOptions": {
        "ecmaVersion": "latest"
    },
    "rules": {
    }
}

        存放的内容大概就是我们使用eslint --init的那些问题的回答,也就是对那些内容进行相应的配置,以便eslint工具可以辨别并进行检测。

当使用配置文件或 package.json 配置 ESLint 的时候,会一层层地叠加使用配置文件。ESLint 将自动在待检测的代码所在的目录里寻找它们,紧接着是父级目录,一直到文件系统的根目录(除非指定 root: true)。ESLint 会将找到的所有配置文件的配置信息合并使用。推荐在项目根目录中的配置文件中设置 "root": true,表明找到该配置文件之后,就不要再继续向上级目录查找配置文件了。通过这种方式,你可以有项目级 ESLint 设置,也有覆盖特定目录的 ESLint 设置。

加完root标志后,再次执行eslint进行检测:

$ npx eslint ./index.js -c .eslintrc.js

/Users/huiquandeng/projects/lg-fed-lp/my-module/eslintusage/index.js
  18:1  error  Parsing error: Unexpected token

✖ 1 problem (1 error, 0 warnings)

就可以发现我们代码中的一个问题,是个error。把它改了。
在次执行检测命令:

$ npx eslint ./index.js                

/Users/huiquandeng/projects/lg-fed-lp/my-module/eslintusage/index.js
   1:7   error  'foo' is assigned a value but never used       no-unused-vars
   3:1   error  More than 1 blank line not allowed             no-multiple-empty-lines
   5:12  error  Missing space before function parentheses      space-before-function-paren
   6:1   error  Expected indentation of 2 spaces but found 4   indent
   6:25  error  Extra semicolon                                semi
   8:1   error  Expected indentation of 2 spaces but found 8   indent
   8:39  error  Extra semicolon                                semi
   8:40  error  Block must not be padded by blank lines        padded-blocks
  10:1   error  More than 1 blank line not allowed             no-multiple-empty-lines
  15:1   error  Expected indentation of 2 spaces but found 0   indent
  15:1   error  'syy' is not defined                           no-undef
  17:2   error  Newline required at end of file but not found  eol-last

✖ 12 problems (12 errors, 0 warnings)
  10 errors and 0 warnings potentially fixable with the `--fix` option.

可以看到检测出来一堆的错误。还提示我们10个error可能使用“--fix”选项进行修复。尝试一下检测命令后加上--fix,结果如下:

$ npx eslint ./index.js --fix

/Users/huiquandeng/projects/lg-fed-lp/my-module/eslintusage/index.js
   1:7  error  'foo' is assigned a value but never used  no-unused-vars
  11:3  error  'syy' is not defined                      no-undef

✖ 2 problems (2 errors, 0 warnings)

果然看到的错误变少了,命令执行完成后,我们的代码被eslint自动修正了一些编码规范的问题(非语法和非使用错误)。

自动修正后的代码如下:

// eslint index.js --fix 命令修正过后的代码
const foo = 123

function fn () {
  console.log('hello')

  console.log('eslint in using')
}

fn()

syy()

可以看出来,一些引号分号使用习惯,缩进空行空格过多等问题都被ESLint自动修正了
 但是作为规范的使用者,一开始不太熟悉的话,还是建议先根据错误提示手动修改一段时间,慢慢熟悉我们的团队编码规范,就可以形成良好的编码习惯,并逐步提高我们的编码水平,尽可能的降低代码编码风格上的出错几率。工具只是为了确保我们最后提交的代码的质量,满足一定的编码规范化标准,方便团队后续的写作开发和维护工作的阅读理解。

最后把剩下的问题解决掉了以后,再次运行eslint检测,
 

~/projects/lg-fed-lp/my-module/eslintusage on  master! ⌚ 15:36:00
$ npx eslint ./index.js --fix

~/projects/lg-fed-lp/my-module/eslintusage on  m

这样就检测不到的代码中有错误提示了。

此外,

当 ESLint 作用于一个目录时,支持使用 .eslintignore 文件来列出一些不需要被 ESLint 检测的文件。.eslintignore 文件是个纯文本文件,可以放在待检测目录的任何父级目录,它将影响到 .eslintignore 文件所在的目录和所有子目录。

与配置文件不同,.eslintignore 文件不会被叠加查找,ESLint 在找到一个 .eslintignore 文件时候就会停止查找上级目录,因此推荐在项目根目录中创建 .eslintignore 文件。

其实不管是否创建 .eslintignore 文件,都会忽略执行 eslint 命令所在目录的 node_modules 目录和 bower_components 里面的所有代码的检测。

# .eslintignore文件
# 忽略 build 目录下的除了 index.js 之外的所有文件的代码检测
build/*
!build/index.js

配置文件里的一些相关的配置大家可以参考该文章和官网。
 

定制ESLint校验规则


ESLint对TypeScript的支持


ESLint结合自动化工具或者webpack

        eslint本身就是一个工具,如果我们的项目使用了自动化构建工具,那么建议把eslint集成到自动化工具中。这样做优点是:集成之后,ESLint一定会工作;与项目统一,管理起来更加方便。

因为ESLint要处理的是我们自己编写的代码,所以我们要在babel处理之前先执行ESLint检测,检测通过且没有错误提示发生再往下交给其他插件进行转换编译压缩等处理。

webpack集成ESLint是以loader的机制来完成的,因为webpack在打包模块之前会先将遇到的模块交给相应的loader进行处理。不过现在eslint已经弃用loader机制了,使用plugin来处理,所以我们可以在webpack项目集成时安装并使用 eslint-webpack-plugin, 在plugins数组中添加new EslintWebpackPlugin({ fix: true })配置,fix为true表示对发现的错误而且eslint能够修复的就及时进行修复。

未使用fix: true 的build结果:

✖ 60 problems (60 errors, 0 warnings)
  55 errors and 0 warnings potentially fixable with the `--fix` option.


webpack 5.73.0 compiled with 1 error in 9942 ms
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

往plugin中添加{fix:true}option后再build,结果就只剩5个需要手动处理的error了: 

✖ 5 problems (5 errors, 0 warnings)


webpack 5.73.0 compiled with 1 error in 10827 ms
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

剩下的error就手工修复一下,再build就可以正常打包了。 


基于ESLint的衍生工具

prettier是一个文档格式化工具,他可以快速方便地帮助我们格式化代码文档或者markdown格式文档。 


StyleLint工具的使用

        stylelint工具的使用跟原理和eslint十分相似,stylelint主要针对的是css/sass/less/postCSS的检测

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值