前端工程化之规范化标准

文章内容输出来源:拉勾大前端高薪训练营

规范化介绍

  • 规范化是我们践行前端工程化中重要的一部分

  • 为什么要有规范标准

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

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

    • 编码前人为的标准约定

    • 通过工具实现lint

    • 常见的规范化实现方法

      • ESLint 工具使用
      • 定制ESLint检验规则
      • ESLint对Typescript的支持
      • ESLint结合自动化工具或者webpack
      • 基于ESLint的衍生工具
      • Stylelint工具的使用

ESLint

  • 介绍

    • 目前最为主流的JavaScript Lint工具,监测JS代码质量
    • ESLint很容易统一开发者的编码风格
    • ESLint可以帮助开发者提升编码能力
  • 安装

    • 初始化项目

      • yarn init --yes
    • 安装ESLint模块为开发依赖

      • npm install eslint --save-dev
    • 通过CLI 命令验证安装结果

      • npx eslint --version
  • 快速上手

    • 1,编写"问题"代码

      • 根目录新建文件01-prepare.js

        • const foo = 123

function fn(){
console.log(‘hello’)
console.log(‘eslint’)

}

fn(

syy()

- npx eslint   .\01-prepare.js

	- 报错: eslint couldn't find a configuration file.

- 解决报错

	- npx eslint --init

		- 会提出一些选项供选择,选择完后根目录下会生成.eslintrc文件

- npx eslint   .\01-prepare.js

	- OK: 可以检测单代码中错误了

- 自动修正

	- npx eslint   .\01-prepare.js --fix
  • 配置文件解析

    • module.exports = {
      // 标记代码的最终运行环境
      env: {
      browser: true,
      es2020: true
      },
      // 用于继承一些共享的配置
      extends: [ ‘standard’],
      // 用来设置语法解析器的相关配置
      parserOptions: {
      // 控制是否允许使用某一个ES版本的语法,影响的只是语法检测,不代表某个成员是否可用,
      // 具体成员是否可用还是得有env中进行配置
      ecmaVersion: 11
      },
      // 用于配置ESLint中某个检验的开启或关闭
      rules: {
      ‘no-alert’: “error”
      },
      // 用于额外声明我们在代码中可以使用的全局成员
      globals: {
      “jQuery”: “readonly”
      }
      }
  • 配置注释

    • 简单理解就是将配置通过注释的方式写在脚本文件当中,然后再去执行代码的检验

    • 项目根目录下新建文件eslint-configuration-comments.js

      • const str1 = ‘${name} is a coder’
        console.log(str1)
    • yarn eslint .\eslint-configuration-comments.js

      • 报错: Unexpected template string expression
    • 修改文件eslint-configuration-comments.js

      • // eslint-disable-line
        const str1 = ‘${name} is a coder’
        console.log(str1)
    • yarn eslint .\eslint-configuration-comments.js

      • OK: 但是会禁用整行检验
    • 修改文件eslint-configuration-comments.js

      • // eslint-disable-line no-template-curly-in-string
        const str1 = ‘${name} is a coder’
        console.log(str1)
    • yarn eslint .\eslint-configuration-comments.js

      • OK: 只禁用指定规则的检验了。
  • 结合自动化工具

    • 优点

      • 集成之后,eslint一定会工作
      • 与项目统一,管理更加方便
    • 准备

      • 克隆代码

        • git clone https://github.com/zce/zce-gulp-demo.git
      • 完成相应的依赖安装

      • 完成eslint模块安装

      • 完成gulp-eslint模块安装

    • 修改根目录下gulpfile.js文件

      • const script =()⥤{
        return src(‘src/assets/scripts/*.js’, { base: ‘src’ })
        .pipe(plugins.eslint())
        .pipe(plugins.babel({ presets: [’@babel/preset-env’] }))
        .pipe(dest(‘temp’)
        .pipe(bs.reload({ stream: true }))
        }

module.exports = {
clean,
build,
develop,
script
}

- 执行script任务

	- npx gulp script

		- 报错: Error: no ESLint configuration found

- 解决报错

	- 初始化eslint配置文件npx eslint --init

- 执行script任务

	- npx gulp script

		- OK:eslint正常执行了

- 修改文件src/assets/scripts/main.js

	-  $(($) ⥤{

const b o d y = body = body=('html, body’)
$(‘scroll_top’).on(‘click’, () ⥤ {
$body.animate({ scrollTop: 0 }, 600)
return false
})
})
const a=1

- 执行script任务

	- npx gulp script

		- OK:有些不合理

- 解决不合理

	- 修改根目录下gulpfile.js文件

		- const script =()⥤{

return src(‘src/assets/scripts/*.js’, { base: ‘src’ })
.pipe(plugins.eslint())
.pipe(plugins.eslint.format())
.pipe(plugins.eslint.failAfterError())
.pipe(plugins.babel({ presets: [’@babel/preset-env’] }))
.pipe(dest(‘temp’)
.pipe(bs.reload({ stream: true }))
}

module.exports = {
clean,
build,
develop,
script
}

- 执行script任务

	- npx gulp script

		- OK~
  • 结合webpack

    • 准备

      • 克隆代码

        • git clone https://github.com/zce/zce-gulp-demo.git
      • 完成相应的依赖安装

      • 完成eslint模块安装

      • 完成eslint-loader模块安装

      • 初始化.eslintrc.js配置文件

    • 项目根目录下webpack.config.js文件

      • const HtmlWebpackPlugin = require(‘html-webpack-plugin’)
        module.exports ={
        mode: ‘production’
        entry: ‘./src/main.js’
        module: {
        rules:[
        {
        test: '.jsKaTeX parse error: Expected 'EOF', got '}' at position 49: …'babel-loader' }̲, { test: '\.js/,
        exclude: /node_modules/,
        use: ‘eslint-loader’,
        enforce: ‘pre’
        },
        {
        test: /.css$/,
        use: [
        ‘style-loader’,
        ‘css-loader’
        ]
        }
        ]
        },
        plugins: [
        new HtmlWebpackPulgin({
        template: ‘src/index.html’
        })
        ]
    • npx webpack

      • OK:eslint成功集成
    • 后续配置

      • module.exports = {
        // 标记代码的最终运行环境
        env: {
        browser: true,
        es2020: true
        },
        // 用于继承一些共享的配置
        extends: [ ‘standard’],
        // 用来设置语法解析器的相关配置
        parserOptions: {
        // 控制是否允许使用某一个ES版本的语法,影响的只是语法检测,不代表某个成员是否可用,
        // 具体成员是否可用还是得有env中进行配置
        ecmaVersion: 11
        },
        // 用于配置ESLint中某个检验的开启或关闭
        rules: {
        ‘react/jsx-uses-react’: 2,
        ‘react/jsx-uses-vars’: 2,
        },
        plugins: [
        ‘react’
        ]
        }

      • npx webpack

        • OK:eslint成功集成
      • src/main.js

        • import React from ‘react’
          import ReactDOM from ‘react-dom’
          import ‘./global.css’
          import App from ‘./components/App’ ReactDOM.render(
          <React.StrictMode>
          <Aрр />
          </React.StrictMode>,
          document.getElementById(‘root’)
          )
      • npm install eslint-plugin-react --save-dev

      • yarn webpack

        • OK~
      • 继承方式

        • module.exports = {
          // 标记代码的最终运行环境
          env: {
          browser: true,
          es2020: true
          },
          // 用于继承一些共享的配置
          extends: [
          ‘standard’,
          ‘plugin:react/recommended’
          ],
          // 用来设置语法解析器的相关配置
          parserOptions: {
          // 控制是否允许使用某一个ES版本的语法,影响的只是语法检测,不代表某个成员是否可用,
          // 具体成员是否可用还是得有env中进行配置
          ecmaVersion: 11
          },
          // 用于配置ESLint中某个检验的开启或关闭
          rules: {
          // ‘react/jsx-uses-react’: 2,
          // ‘react/jsx-uses-vars’: 2,
          },
          // plugins: [
          // ‘react’
          // ]
          }
        • yarn webpack
  • 现代化项目集成ESLint

    • npm install @vue/cli -g

    • vue create syy-vue-app

      • 根据需要选择对应选项,选择后生成基本项目结构
    • cd syy-vue-app

    • npm run serve

      • OK~
  • eslint检查TypeScript

    • npx eslint --init

      • 选项中选择需要TypeScript
    • 项目根目录新建index.ts

      • function foo(ms: string) {
        console.log(msg)
        }

foo(‘hello typescript’)

- 修改eslint配置

	- module.exports = { 

// 标记代码的最终运行环境
env: {
browser: true,
es2020: true
},
// 用于继承一些共享的配置
extends: [
‘standard’,
‘plugin:react/recommended’
],
parser: ‘@typescript-eslint/parser’,
// 用来设置语法解析器的相关配置
parserOptions: {
// 控制是否允许使用某一个ES版本的语法,影响的只是语法检测,不代表某个成员是否可用,
// 具体成员是否可用还是得有env中进行配置
ecmaVersion: 11
},
// 用于配置ESLint中某个检验的开启或关闭
rules: {
// ‘react/jsx-uses-react’: 2,
// ‘react/jsx-uses-vars’: 2,
},
// plugins: [
// ‘react’
// ]
}

- npx eslint  .\index.ts

	- ok~q

Stylelint的认识

  • 使用介绍

    • 提供默认的代码检查规则
    • 提供CLI工具,快速调用
    • 通过插件支持Sass Less PostCSS
    • 支持Gulp或Webpack集成
  • 安装

    • npm install stylelint -D
  • 测试

    • npx stylelint ./index.css

      • 报错: No configuration provided for
  • 解决报错

    • 项目根目录下添加.stylelintrc.js文件

      • module.exports ={
        extends: ‘stylelint-config-standard’
        }
    • npm install stylelint-config-standard -D

  • npx stylelint ./index.css

    • OK:可以找到css中的问题了
  • 自动修复

    • npx stylelint ./index.css --fix
  • 检查Sass代码

    • npm install stylelint-config-sass-guidelines -D
  • 修改.stylelintrc.js文件

    • module.exports ={
      extends: [
      ‘stylelint-config-standard’,
      ‘stylelint-config-sass-guidelines’
      ]
      }
  • npx stylelint ./index.sass

    • OK:可以找到sass中的问题了

Prettier的使用

  • 通用的前端代码格式化工具

  • 安装

    • npm install prettier -D
  • 使用

    • npx prettier style.css

      • 将格式化的代码直接输出到控制台中
    • npx prettier style.css --write

      • 将格式化的代码直接覆盖写入该文件
    • 批量格式化

      • npx prettier . --write

Git Hooks

  • 介绍

    • 背景

      • 问题: 代码提交到仓库之前未执行lint操作
      • 解决: 通过Git Hooks在代码提交前强制lint
    • Git Hooks也称为Git钩子,每个钩子都对应一个任务

    • 通过shell脚本可以编写钩子任务触发时要具体执行的操作

    • .git隐藏目录文件夹中有个叫hooks的文件夹📂,里面存放了一些sample文件,每一个sample文件就代表一种钩子

  • eslint结合Git Hooks

    • 背景

      • 问题

        • 很多前端开发者并不擅长使用shell
      • 解决

        • Husky可以实现Git Hooks的使用需求
    • 安装

      • npm install husky -D
    • 在项目根目录下package.json文件中增加husky配置

      • “husky”: {
        hooks: {
        “pre-commit”: “npm run test”
        }
        }
    • 项目根目录下新建index.js文件

      • const a = 1

2222

- git add  .
- git commit -m "333"
- 在项目根目录下package.json文件中修改scripts属性

	- "scripts": {

“test” : “eslint./index.js”
}

- 修改index.js文件

	- const a = 1

3333

- git add  .
- git commit -m "444"

	- OK~

- 自动修复并将修正后代码放入暂存区

	- 安装

		- npm install lint-staged -D

	- package.json中增加配置

		- "scripts": {

“test” : “eslint./index.js”,
“precommit”: “lint-staged”
},

“lint-staged”: {
“*.js”: [
“eslint”,
“git add”
]
},
“husky”: {
hooks: {
“pre-commit”: “npm run precommit”
}
}

	- 修改index.js文件

		- const a = 1

4444

	- git add  .
	- git commit -m "555"

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值