中國新聞社招聘2023年褲子seo關(guān)鍵詞
在日常開發(fā)過程中,經(jīng)常會碰到代碼格式化不一致的問題,還要就是 js 代碼語法錯誤等沒有及時發(fā)行改正,下面就介紹一下如何使用
eslint
、prettier
、husky
、lint-staged
、commitizen
來規(guī)范代碼格式和提高代碼質(zhì)量的方法。
目錄
- 準(zhǔn)備工作
- 代碼檢測
- 代碼格式化
- Git 規(guī)范
準(zhǔn)備工作
新建項目
新建一個測試項目。
mkdir code
cd code
npm init -y
git init
測試文件
<!-- index.html -->
<div><h1>Hello</h1><p>Hello,code!</p>
</div>
/* index.css */
body {width: 10px;
}
// index.js
function add(a, b) {return a + b;
}
代碼檢測
這里主要是使用eslint
來檢測代碼。
eslint 官網(wǎng)
安裝依賴包
npm install eslint
生成配置文件
- 安裝配置
npm init @eslint/config
- 選擇類型
? How would you like to use ESLint? ...To check syntax only
> To check syntax and find problemsTo check syntax, find problems, and enforce code style
- 選擇模塊
? What type of modules does your project use? ...
> JavaScript modules (import/export)CommonJS (require/exports)None of these
- 選擇框架
? Which framework does your project use? ...React
> Vue.jsNone of these
- 是否使用 ts
? Does your project use TypeScript? ? No / Yes
- 運(yùn)行環(huán)境
? Where does your code run? ... (Press <space> to select, <a> to toggle all, <i> to invert selection)
√ Browser
√ Node
- 文件格式
? What format do you want your config file to be in? ...
> JavaScriptYAMLJSON
- 安裝依賴
Local ESLint installation not found.
The config that you've selected requires the following dependencies:eslint-plugin-vue@latest eslint@latest
? Would you like to install them now? ? No / Yes
- 選擇包管理器
? Which package manager do you want to use? ...npmyarn
> pnpm
等待安裝完成。
Installing eslint-plugin-vue@latest, eslint@latest
npm WARN idealTree Removing dependencies.eslint in favor of devDependencies.eslintadded 12 packages in 3s
A config file was generated, but the config file itself may not follow your linting rules.
Successfully created .eslintrc.js file in D:\code
下面是生成的配置文件。
module.exports = {env: {browser: true,es2021: true,},extends: ["eslint:recommended", "plugin:vue/vue3-essential"],parserOptions: {ecmaVersion: "latest",sourceType: "module",},plugins: ["vue"],rules: {},
};
忽略文件.eslintignore
# /node_modules/* and /bower_components/* ignored by default
# Ignore built files except build/index.js
.eslintignore
node_modules
dist
.eslintrc.js
.prettierrc.js
shell 腳本
可以寫一個簡單的 shell 腳本detect.sh
來檢測。
#!/bin/bashecho "代碼檢測工具"
if [ "$1" = "-p" ];thenif [ "$2" ];thenif [ -f $2 ];thenecho "正在檢測中..."eslint --config ".eslintrc.js" --fix $2echo "代碼檢測完畢!"elseecho "文件不存在!"fielseecho "路徑錯誤!"fi
elseecho "命令錯誤!"
fi
使用方法:sh detect.sh -p {文件路徑}
例如:sh detect.sh -p index.js
結(jié)果是:
代碼檢測工具
正在檢測中...
代碼檢測完畢!
代碼格式化
這里主要是用prettier
來進(jìn)行代碼格式化。
prettier 官網(wǎng)
安裝 prettier
- 全局安裝
npm i prettier -g
- 項目安裝
npm i prettier -S
配置文件
配置文件參考
// .prettierrc.js
//配置文檔參考:https://prettier.io/docs/en/options
module.exports = {printWidth: 120, // 指定打印機(jī)將換行的行長度tabWidth: 2, // 指定每個縮進(jìn)級別的空格數(shù)useTabs: false, // 指定每個縮進(jìn)級別的空格數(shù)semi: true, // 在語句末尾打印分號singleQuote: false, // 使用單引號而不是雙引號quoteProps: "as-needed", // 使用單引號而不是雙引號/*** "as-needed"- 僅在需要時在對象屬性周圍添加引號。"consistent"- 如果對象中至少有一個屬性需要引號,則引用所有屬性。"preserve"- 尊重對象屬性中引號的輸入使用。*/jsxSingleQuote: false, // 在 JSX 中使用單引號而不是雙引號trailingComma: "all", // 盡可能以多行逗號分隔的語法結(jié)構(gòu)打印尾隨逗號bracketSpacing: true, // 在對象文本的方括號之間打印空格bracketSameLine: false, // 在對象文本的方括號之間打印空格arrowParens: "always", // 將多行 HTML(HTML、JSX、Vue、Angular)元素放在最后一行的末尾,而不是單獨(dú)放在下一行(不適用于自閉合元素)requirePragma: false, // 在唯一箭頭函數(shù)參數(shù)兩邊加上括號// stdinFilepath: "", // 指定用于推斷要使用的分析器的文件名// range-start// rangeStart: 0, // 向后到包含所選語句的第一行的開頭// rangeEnd: 99999, // 轉(zhuǎn)發(fā)到所選語句的末尾requirePragma: false, // Prettier 可以將自身限制為僅格式化文件頂部包含特殊注釋(稱為雜注)的文件insertPragma: false, // Prettier 可以將自身限制為僅格式化文件頂部包含特殊注釋(稱為雜注)的文件proseWrap: "preserve", // 默認(rèn)情況下,Prettier 不會更改 markdown 文本中的換行,因為某些服務(wù)使用換行敏感的渲染器htmlWhitespaceSensitivity: "css", // 默認(rèn)情況下,Prettier 不會更改 markdown 文本中的換行/*** css 遵循 CSS 屬性的默認(rèn)值;* strict 所有標(biāo)簽周圍的空格(或缺少空格)被認(rèn)為是重要的;* ignore 所有標(biāo)簽周圍的空格(或缺少空格)被認(rèn)為是微不足道的*/vueIndentScriptAndStyle: false, // 是否縮進(jìn) Vue 文件中的代碼和標(biāo)簽endOfLine: "lf", // 正確顯示行尾, lf 僅換行;crlf 回車符 + 換行符;cr 僅回車符;auto 維護(hù)現(xiàn)有的行尾singleAttributePerLine: false, // 在 HTML、Vue 和 JSX 中每行強(qiáng)制使用單個屬性parser: "html", // 指定要使用的分析器
};
忽略文件.prettierignore
# Ignore artifacts:
build
dist# Ignore all HTML files:
*.html
常用命令
下面是根據(jù)指定的配置文件.prettierrc.js
對index.js
腳本進(jìn)行代碼格式化。
prettier --config .prettierrc.js --write index.js
沖突解決
eslint 和 prettier 規(guī)則會發(fā)生沖突,下面是解決沖突的方法。
- 安裝
npm i eslint-config-prettier eslint-plugin-prettier -D
- 配置
在.eslintrc.js
文件的extends
和plugins
中添加prettier
即可。
module.exports = {// ...extends: ["eslint:recommended", "plugin:vue/vue3-essential", "prettier"],plugins: ["vue", "prettier"],// ...
};
格式化腳本
可以寫一個簡單的 shell 腳本format.sh
來檢測。
#!/bin/bashecho "代碼格式化工具"
if [ "$1" = "-p" ];thenif [ "$2" ];thenif [ -f $2 ];thenecho "正在格式化..."prettier --config ".prettierrc.js" --write $2echo "格式化完畢!"elseecho "文件不存在!"fielseecho "路徑錯誤!"fi
elseecho "命令錯誤!"
fi
使用方法:sh format.sh -p {文件路徑}
例如:sh format.sh -p index.js
結(jié)果是:
代碼格式化工具
正在格式化...
index.js 107ms
格式化完畢!
Git 規(guī)范
運(yùn)行腳本
lint-staged
是一個可以在 Git 暫存區(qū)中的文件上執(zhí)行腳本命令。
- 安裝
npm i lint-staged -S
- 配置
在package.json
中配置。
{//..."lint-staged": {"./src/*.{js,ts}": ["eslint --fix", "prettier --config .prettierrc.js --write"]}//...
}
鉤子工具
husky
是一個 Git 鉤子工具,可以在 Git 事件發(fā)生時執(zhí)行腳本,進(jìn)行代碼格式化、測試等操作。
常見鉤子
- pre-commit
在執(zhí)行 Git commit 命令之前觸發(fā),用于在提交代碼前進(jìn)行代碼檢查、格式化、測試等操作。
- commit-msg
在提交消息(commit message)被創(chuàng)建后,但提交操作尚未完成之前觸發(fā),用于校驗提交消息的格式和內(nèi)容。
- pre-push
在執(zhí)行 Git push 命令之前觸發(fā),用于在推送代碼前進(jìn)行額外檢查、測試等操作。
husky 安裝配置
- 安裝
npm i husky -S
- 啟用鉤子
npm pkg set scripts.prepare="husky install"
# 或者
npx husky install
安裝成功后會在package.json
文件中生成以下命令。
{//..."scripts": {"prepare": "husky install"}//...
}
- 運(yùn)行腳本
npm run prepare
安裝成功后會在根目錄出現(xiàn)一個.husky
目錄。
- 創(chuàng)建掛鉤
pre-commit
npx husky add .husky/pre-commit
# 或者
npx husky add .husky/commit-msg
- 配置代碼檢測
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"npx --no-install lint-staged
提交規(guī)范
cz-conventional-changelog
是一個提交消息規(guī)范,規(guī)定了提交消息的格式和結(jié)構(gòu)。
- 安裝
npm i commitizen cz-conventional-changelog -S
- 配置
在package.json
中配置。
{//..."scripts": {// ..."cz": "git-cz"},"config": {"commitizen": {"path": "cz-conventional-changelog"}}//...
}
- 運(yùn)行
git status
git add .
npm run cz
接下來就根據(jù)你的情況選擇填寫消息內(nèi)容。
? Select the type of change that you're committing: (Use arrow keys)
> feat: A new featurefix: A bug fixdocs: Documentation only changesstyle: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)refactor: A code change that neither fixes a bug nor adds a featureperf: A code change that improves performancetest: Adding missing tests or correcting existing tests
接下來就會自動執(zhí)行剛剛填寫的腳本,執(zhí)行代碼檢測和格式化,下面就是其中的一部分執(zhí)行內(nèi)容。
[STARTED] Preparing lint-staged...
[COMPLETED] Preparing lint-staged...
[STARTED] Running tasks for staged files...
[STARTED] package.json — 11 files
[STARTED] ./src/*.{js,ts} — 1 file
[STARTED] eslint --fix
[COMPLETED] eslint --fix
[STARTED] prettier --config .prettierrc.js --write
[COMPLETED] prettier --config .prettierrc.js --write
[COMPLETED] ./src/*.{js,ts} — 1 file
[COMPLETED] package.json — 11 files
[COMPLETED] Running tasks for staged files...
[STARTED] Applying modifications from tasks...
[COMPLETED] Applying modifications from tasks...
如果有問題就會報錯,你更改報錯的地方代碼就重新提交即可。
最后
以上就是前端代碼格式化規(guī)范總結(jié)的主要內(nèi)容,有不足之處,請多多指正。