规范化标准

为什么要有规范化标准

  • 软件开发需要多人协同
  • 不同开发者具有不同的编码习惯和喜好
  • 不同的喜好增加项目维护成本
  • 每个项目或者团队需要明确统一的标准

哪里需要规范化标准

  • 代码、文档、甚至是提交日志
  • 开发过程中人为编写的成果图
  • 代码标准化规范最为重要

实施规范化的方法

  • 编码前人为的标准约定
  • 通过工具实现Lint

常见的规范化实现方式

  • ESLint 工具使用
  • 定制ESLint校验规则
  • ESLint对TypeScript的支持
  • ESLint结合自动化工具或者Webpack
  • 基于ESLint的衍生工具
  • StyleLint工具的使用


一、ESLint

1. ESLint介绍

  • 最为主流的JavaScript Lint工具,检测JS代码质量
  • ESLint很容易统一开发者的编码风格(缩进,换行,分号,空格等)
  • ESLint可以帮助开发者提升编码能力

    2. ESLInt安装

  • 初始化项目: yarn init -y

  • 安装ESLint模块为开发依赖: yarn add eslint —dev
  • 通过CLI命令验证安装结果:yarn eslint -v

    3. ESLint 检查步骤

  • 编写“问题”代码

  • 使用eslint执行检测 : 执行yarn eslint 01-prepare.js,执行自动修复yarn eslint 01-prepare.js —fix
  • 完成eslint使用配置 : yarn eslint —init
  • image.png

    一般选择第三个

    4. ESLint配置文件解析

    1. module.exports = {
    2. env: {
    3. // 运行的环境,决定了有哪些默认全局变量
    4. browser: true,
    5. es2020: true
    6. },
    7. // eslint 继承的共享配置
    8. extends: [
    9. 'standard'
    10. ],
    11. // 设置语法解析器,控制是否允许使用某个版本的语法
    12. parserOptions: {
    13. ecmaVersion: 11
    14. },
    15. // 控制某个校验规则的开启和关闭
    16. rules: {
    17. 'no-alert': 'error'
    18. },
    19. // 添加自定义的全局变量
    20. globals: {
    21. "$": 'readonly',
    22. }
    23. }

    5. ESLint配置注释

    将配置写在代码的注释中,然后再对代码进行校验

    const str1 = "${name} is coder" // eslint-disable-line no-template-curly-in-string
    console.log(str1)
    

    6. ESLint 结合自动化工具

  • 集成之后,ESLint一定会工作

  • 与项目统一,管理更加方便

    7. ESLint结合Webpack

    eslint通过loader形式校验JavaScript代码

前置工作:

  • git clone 仓库 https://github.com/zce/zce-react-app.git
  • 安装对应模块
  • 安装eslint模块
  • 安装eslint-loader模块

    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          use: ['babel-loader']
        },
        {
          test: /\.js$/,
          exclude: /node_modules/,
          use: ['eslint-loader'],
          enforce:'pre'
        }
      ]
    },
    
  • 初始化.eslintrc.js配置文件

后续配置:
yarn add eslint-plugin-react

rules: {
  'react/jsx-uses-react': 2,
   'react/jsx-uses-vars': 2
},
plugins: [
  'react'
]
-----------------------
 //或者直接用继承插件
extends: [
    'standard',
        'plugin:react/recommended'  
],

8 现代化项目集成ESLint

vue和react的cli工具中有已经集成,创建项目时选择即可

9 ESLint检查TypeScript

初始化eslint的时候选择typescript即可

parser: '@typescript-eslint/parser'