对代码进行格式化,是程序员的平常。格式化很爽,可是配置相关的规则、安装对应插件却很烦。与其每次碰到问题再慢慢排查,不如一次性融会贯通。javascript
咱们能够按照修改后是否会影响程序运行结果来把风格分为两个部分。例以下面的代码css
var a= 1; if (a=='1') console.log(true )
格式,简单来讲就是变量后面是否须要空格,语句后面是否须要分号等,这一类不管如何改动,都不会影响代码运行结果的部分。对格式进行改变叫格式化。前端
使用以下规则对代码进行 format:java
var a = 1; if ( a == '1' ) console.log( true );
源码,与格式相对的,是被修改以后会切实影响代码运行结果的部分。对源码进行改变叫源动做node
使用以下规则对代码进行 source action:webpack
const
定义===
,禁止使用 ==
const a = 1; if ( a === '1' ) console.log( true );
格式加源码,构成了代码风格git
定义来源: vscode 任意选中一段代码以后右键
风格固然是有各类各样的,有的工具能够设定本身的风格,有的工具强制使用特定风格。为了便于理解,本文只介绍业界最主流的工具(也不多有人用其余的)程序员
Prettier 专一于 Format,基本支持了前端项目相关的全部文件类型,包括但不限于es6
Prettier 最大的特色是独裁,在自身规定的几百上千条 Format 规则中,可配置的仅有 20 条。这也致使其余工具与 Prettier 并存时,都须要迁就 Prettier 的规则github
ESLint 是目前全部 Lint 工具中使用最普遍的(前端范围内)。
计算机科学中, lint 是一种工具程序的名称,它用来标记 源代码中,某些可疑的、不具结构性(可能形成bug)的段落。它是一种 静态程序分析工具,最先适用于 C语言,在 UNIX平台上开发出来。后来它成为通用术语,可用于描述在任何一种计算机程序语言中,用来标记源代码中有疑义段落的工具。
—— wiki
ESlint 可配置的范围,包括 Format 和 Source,可是仅限于能够被转换成 AST 的代码,对于 CSS、HTML 等都无能为力(这也是为何须要同时使用 ESLint 和 Prettier 的缘由)
前端开发基本等同于 HTML、JavaScript 和 CSS 开发。经过 Prettier + ESLint,对于风格中的 Format 已经彻底统一,JavaScript 中的 Source 也被统一。因此如今还剩下基本能够忽略的 HTML 和 CSS 中的 Source 部分
咱们选择使用 stylelint 来处理 CSS 相关 Source
这样基本能够限定前端开发过程当中的全部风格
HTML | JavaScript | CSS | |
---|---|---|---|
Format | prettier | prettier | prettier |
Source | 无 | ESlint | stylelint |
一般项目中使用风格工具,有三种途径
先模拟一下项目中开发需求的流程
使用 webpack 编译项目
任何流程没有控制住,都有可能形成设定之外的代码风格
不管是经过函数、命令行或者插件来使用,风格化的过程基本均可以抽象为以下公式。
Result = format(sourceAction(src, config)) = Tool(src, config) // 最终风格 = 格式化(源动做(源码,配置)) = 工具(源码,配置)
源码为常量。只要保证工具版本统一,配置相同,则不一样途径均也能够得出相同的结果。规则和工具的选择历来不是难点,难点在于保证工具、配置的统一
接下来介绍如何保证 A、B、C 三种途径的统一
ESlint: The extension uses the ESLint library installed in the opened workspace folder. If the folder doesn't provide one the extension looks for a global install version.
Prettier: This extension will use prettier from your project's local dependencies (recommended)...
stylelint: The extension uses the stylelint library installed in the opened workspace folder...
根据各个工具的官方插件文档说明,插件会优先使用项目中的对应库 node_modules
,若是不存在则使用全局库。
ESLint 插件目前能够指定配置文件,若是不指定会读取 package.json 同级的配置文件
eslint.options: options to configure how ESLint is started using the ESLint CLI Engine API. Defaults to an empty option bag. An example to point to a custom .eslintrc.json file is:
{ "eslint.options": { "configFile": "C:/mydirectory/.eslintrc.json" } }
Prettier 的配置能够来源于三处,按优先级排列
.editorconfig
实际使用中,使用第一个 package.json 同级的配置文件便可
与 Prettier 相似
const StyleLintPluginfrom = require('stylelint-webpack-plugin'); //... { test: /\.(j|t)sx?$/, use: [ { loader: 'babel-loader', }, { loader: 'eslint-loader', options: { configFile: getWorkSpacePath('.eslintrc.js'), } }, ], } //... plugins: [ new StyleLintPluginfrom({ configFile: getWorkSpacePath('.stylelintrc.js'), }) ] //...
全部库都须要安装在项目的 node_modules
中, eslint-loader 同时依赖于 eslint 库(stylelint-webpack-plugin 相似)
全部工具基本均可以在 option 中指定配置文件
首先须要在 node_modules 中安装有对应的库,而后在 package.json 中设置对应脚本
{ //... "scripts": { "eslint": "eslint", "prettier": "prettier", "stylelint": "stylelint", }, //... }
以后能够在命令行中使用
yarn eslint --fix -c, --config path::String Use this configuration, overriding .eslintrc.* config options if present yarn prettier --write --config ./my/.prettierrc yarn stylelint --fix --config ./my/.stylelintrc
全部工具在使用都可以指定配置文件
因此
**node_modules**
中,保证不使用全局依赖node_modules
同级,因此建议因此配置文件都放在这一层首先引入 Prettier,咱们全部的 format 都使用 Prettier 来完成。
yarn add prettier -D
安装官方推荐的编译器插件 Prettier - Code formatter
(此处只考虑 VSCode),设置工做区的 .vscode/setting.json
切记必定要关闭其余带有格式化功能的插件,不然会发生冲突。特别是使用 VUE 框架时,记得关闭 vetur 的格式化。同时记得检查一下全局范围的 setting.json
,注释掉全部 format 相关的配置
{ // 保存时自动 Format "editor.formatOnSave": true, // 关闭 vetur 格式化 "vetur.format.enable": false, }
为了告诉其余协同开发的同事,安装正确的 Prettier 插件,添加插件名在 .vscode/extensions.json
中,同时把其余容易干扰格式化的插件设置为不推荐。
这样其余人在首次安装项目的同时也会收到对应的提示了。
{ "recommendations": [ "esbenp.prettier-vscode", ], "unwantedRecommendations": ["hookyqr.beautify"] }
在 package.json
同级建立 Prettier 的配置文件
// prettier.config.js or .prettierrc.js module.exports = { trailingComma: "es5", tabWidth: 4, semi: false, singleQuote: true, };
git 提交本次修改(尤为是 .vscode 文件夹)。以后任何人开发这个项目,只要安装了正确的插件,写出来的代码风格确定都是统一的了
假设有一个同事头铁,就是不正确安装插件和配置编译器。他提交代码的风格就没法获得统一,因此须要再增长一层保险,在 git commit 时候须要校验全部改动过的文件,对这些文件使用 prettier --write
。
git commit 时触发、校验全部改动过的文件。这两个功能分别是两个插件
它能运行Githooks诸如 Pre-commit、pre-receive 和 post-receive。
用以在各个阶段触发不一样校验,通常配合各类 lint 使用
当项目文件比较多的时候,若是每次改动都对全部文件进行校验。势必致使等待时间变长。 解决上面的痛点就须要使用 lint-staged。它只会校验你提交或者说你修改的部份内容。
yarn add husky lint-staged -D
在 package.json
中添加字段
"husky": { "hooks": { "pre-commit": "lint-staged" } }, "lint-staged": { // src 目录下任意文件有改动,都使用 prettier --write 格式化以后再提交 "src/**/*.*": [ "prettier --write", "git add" ] }
这样基本就能保证项目的万无一失了(一失在于开发者删除 husky、lint-stage 配置🤦♂️)
Prettier 只提供了风格中 Format 的部分,对于 Source,还须要接入其余工具。
流程基本和接入 Prettier 同样
安装 ESLint
stylelint
,并修改 setting.json
yarn add eslint stylelint -D
注意 formatOnSave
、codeActionsOnSave
二者的区别。以前说过,由 Prettier 进行全部的 format,而后再针对不一样类型的文件使用各类的 Soruce action
相关讨论: https://github.com/microsoft/vscode/issues/87096#issuecomment-567750791
{ // 保存时自动 Format "editor.formatOnSave": true, // 保存时自动 Source action "editor.codeActionsOnSave": { "source.fixAll": true, // 开启全部工具的 source action //"source.fixAll.eslint": true, // 开启 ESLint 的 source action //"source.fixAll.stylelint": true, // 开启 stylelint 的 source action }, "vetur.format.enable": false, }
修改 extensions.json
{ "recommendations": [ "esbenp.prettier-vscode", "dbaeumer.vscode-eslint", "stylelint.vscode-stylelint" ], "unwantedRecommendations": ["hookyqr.beautify"] }
在 package.json
同级建立 ESlint、stylelint 的配置文件,具体如何设置此处就不说明了。要注意的就是必定要给 Prettier 的设置让位
**
给 ESLint、stylelint 安装兼容 prettier 的插件
yarn add eslint-config-prettier stylelint-config-prettier -D
// .eslintrc.js module.exports = { //... env: { browser: true, es6: true, }, extends: ["eslint:recommended", "prettier"], plugins: [], rules: {}, //... };
// .stylelintrc.js module.exports = { //... extends: ["stylelint-config-prettier"], plugins: [], rules: {}, //... };
不少 Source 问题会要求用户手动更改,因此须要及时提示。插件虽然会提示,但不会影响代码编译结果,因此须要在编译过程当中校验
详见以前的 B - webpack 引入相关 loader、plugin 段落
修改 package.json
"husky": { "hooks": { "pre-commit": "lint-staged" } }, "lint-staged": { // src 目录下任意文件有改动,都使用 prettier --write 格式化以后再提交 "src/**/*.js": [ "eslint --fix", "prettier --write", "git add" ], "src/**/*.css":[ "stylelint --fix", "prettier --write", "git add" ] }
至此,风格统一相关的全部流程都已经覆盖到了!