篇十:大前端基础之前端规范化标准笔记

306 阅读5分钟

文章输出主要来源:拉勾大前端高新训练营(链接) 与 各技术官方文档。小哥哥小姐姐请不要嫌弃啰嗦,下面肯定都是干货。

1.ESLint的使用

ESLint目标是提供一个插件化的javascript代码检测工具,借助ESLint可以统一代码的编码风格,帮助开发者提高编码能力。中文网站:eslint.bootcss.com/,英文官网:https… 英文官网中的文档为最新的文档,有些内容在中文中没有列出。

1.1 基本使用

安装:yarn add eslint -D

eslint初始化:yarn eslint --init,根据自己的需求与cli进行交互,生成eslint配置文件

使用:yarn eslint ./src/index.js可以检查代码中的错误,yarn eslint ./src/index.js --fix可以修复一些代码风格问题,并报出一些无法修复的错误,通过报错可以准确修改问题代码。

1.2 配置文件

以下为上述通过yarn eslint --init生成的配置文件

module.exports = {
  env: {
    browser: true,
    es2021: true
  },
  extends: [
    'standard'
  ],
  parserOptions: {
    ecmaVersion: 12,
    sourceType: 'module'
  },
  rules: {
  }
}

以下为一些配置选项的说明:

env: 配置环境信息,其中可以同时配置多个环境,不会存在冲突问题,可选配置为(选自eslint英文官网)

  • browser - browser global variables.
  • node - Node.js global variables and Node.js scoping.
  • commonjs - CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack).
  • shared-node-browser - Globals common to both Node.js and Browser.
  • es6 - enable all ECMAScript 6 features except for modules (this automatically sets the ecmaVersion parser option to 6).
  • es2017 - adds all ECMAScript 2017 globals and automatically sets the ecmaVersion parser option to 8.
  • es2020 - adds all ECMAScript 2020 globals and automatically sets the ecmaVersion parser option to 11.
  • es2021 - adds all ECMAScript 2021 globals and automatically sets the ecmaVersion parser option to 12.
  • worker - web workers global variables.
  • amd - defines require() and define() as global variables as per the amd spec.
  • mocha - adds all of the Mocha testing global variables.
  • jasmine - adds all of the Jasmine testing global variables for version 1.3 and 2.0.
  • jest - Jest global variables.
  • phantomjs - PhantomJS global variables.
  • protractor - Protractor global variables.
  • qunit - QUnit global variables.
  • jquery - jQuery global variables.
  • prototypejs - Prototype.js global variables.
  • shelljs - ShellJS global variables.
  • meteor - Meteor global variables.
  • mongo - MongoDB global variables.
  • applescript - AppleScript global variables.
  • nashorn - Java 8 Nashorn global variables.
  • serviceworker - Service Worker global variables.
  • atomtest - Atom test helper globals.
  • embertest - Ember test helper globals.
  • webextensions - WebExtensions globals.
  • greasemonkey - GreaseMonkey globals.

**extends:**extents可以继承一些基础配置中已启用的规则,例如以上继承了standard标准中定义的规则。可以通过在数组中添加多个基础配置,同时继承多个基础配置。

**parserOptions:**可以做一些语法检测相关的配置。其中ecmaVersion设置使用ES语法的版本,上述设置12即ES2021,如果ES ModulesourceType可以设置为module,使用script方式则不能使用ES Module。parserOptions其他配置可以查看eslint.bootcss.com/docs/user-g….

parserOptions中的配置仅仅是对语法进行检测,如果要启用全局变量例如Primise的支持,需要通过env中配置es语法,例如上述中的es2021: true

**rules:**可以配置启动的规则以及各自的错误级别,错误级别有以下三种:

  • "off"0 - 关闭规则
  • "warn"1 - 开启规则,使用警告级别的错误:warn (不会导致程序退出)
  • "error"2 - 开启规则,使用错误级别的错误:error (当被触发的时候,程序会退出)

例:

module.exports = {
  rules: {
    "no-alert": "error" // 使用alert就会报错
  }
}

ESLint所有规则(中文网站):eslint.bootcss.com/docs/rules/

英文官网:eslint.org/docs/rules/

**globals:**配置全局成员,例如引用了jQuery可以通过globals添加jQuery全局变量

module.exports = {
  "globals": {
        "jQuery": "readonly",
        "$": "readonly"
    }
}

1.3 配置注释

文档:eslint.cn/docs/user-g…

对于代码中的某些特殊的代码,如果不希望进行ESLint校验,则可以通过注释进行忽略,其他代码正常校验。

常见注释用法

禁用代码块

function foo () {
  /* eslint-disable */
  console.log('hello world')
  console.log('hi')
  /* eslint-enable */
  console.log('此处使用报错')
}

foo()

指定禁用规则

function foo () {
  /* eslint-disable no-alert, no-console */
  console.log('hello world')
  console.log('hi')
  /* eslint-enable no-alert, no-console */
}

单行注释

function foo () {
  console.log('foo'); // eslint-disable-line

  // eslint-disable-next-line
  console.log('foo');

  /* eslint-disable-next-line */
  console.log('foo');

  console.log('foo'); /* eslint-disable-line */
}

1.4 使用插件

eslint支持使用第三方插件,可以通过npm包进行插件的安装。

如果项目使用了react,在使用eslint --init时可以在框架询问时进行选择,此时就会额外安装react的插件,用法为:

module.exports = {
  ...
  extends: [
    'plugin:react/recommended', // 使用插件的推荐配置:插件名:插件配置
    'standard'
  ],
  plugins: [
    'react' // 使用插件
  ],
}

2. StyleLint简单介绍

StyleLint与ESLint类似,但它是用来对CSS代码做lint的,官网:stylelint.io/user-guide/…

使用方式:

  1. 安装:yarn add stylelint stylelint-config-standard -D

  2. 创建.stylelintrc

    {
      "extends": "stylelint-config-standard"
    }
    
  3. 使用:npx stylelint "**/*.css"

除了对css做校验,还可以针对sass,less,css-in-js等方式的样式文件做校验。

3. Prettier基本使用

通过Prettier可以对代码进行格式化,例如js,jsx,vue,css,less,sass等,官网:prettier.io/docs/en/ind…

安装: yarn add prettier -D

使用: npx prettier --write .oryarn prettier --write ., --write会将格式化后的代码重写进之前的文件中。--check--write类似,但只会进行检查,不会进行重写。

**配置文件:**通过配置文件可以自定义format的选项 prettier.io/docs/en/con…: prettier.io/docs/en/opt…

配置文件可以是json,js, YAML,TCML等格式

JSON格式例子:

{
  "trailingComma": "es5",
  "tabWidth": 4,
  "semi": false,
  "singleQuote": true
}

常见使用方式:

一般使用时会将其放在package.json文件中,通过git hooks在commit提交之前自动进行触发format,这配合lint-stagedhusky进行使用, 示例:(选自官方文档)

{
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "**/*": "prettier --write --ignore-unknown"
  }
}

4. Git Hooks简单使用

通过 husky 工具可以对不同的git hooks添加不同的任务,在一定时机下触发任务的执行。

使用方式:

安装: yarn add husky -D

**使用:**在package.json中添加husky字段,里面的hooks配置中可以对git hooks进行配置

{
  "husky": {
    "hooks": {
      "pre-commit": "eslint --fix"
    }
  },
}

配合lint-staged:

husky的使用会配合lint-staged一起使用,lint-stage的作用是对文件进行过滤,会对命中commit的文件进行lint,而不需要对所有的文件一股脑全部进行检查,在多人合作的项目中,如果没有过滤直接对所有的代码进行lint,可能会导致lint时间较长,或更改了他人的代码。

使用方式:在package.json中添加lint-staged字段

{
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.js": ["eslint --fix", "git add ."]
  }
}