前端项目规范初始化

103 阅读2分钟

ESLint

// 安装 eslint
yarn add eslint -D

// 初始化 eslint 跟着指引配置
npx eslint --init

随后添加.eslintignore忽略不需要校验的文件

package.json中加入scripts命令

"scripts": {
  "lint": "eslint --fix --ext .js,.ts ./packages",
},

如果需要vscode保存自动格式化代码可以写入配置settings.json

"editor.formatOnSave": false,
"editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
},
"eslint.validate": ["typescript", "javascript", "vue"]

记得安装ESLint插件

EditorConfig

安装EditorConfig for VS Code插件

这个插件可以让编译器读取配置文件,并且按照配置文件里面的规定来格式化代码,有了这个插件,只要定义好一份配置文件,就算团队成员用的编译器不同,也能够输出风格统一的代码

创建.editorconfig文件,这个文件里面定义的代码规范规则会高于编译器默认的代码规范规则

root = true

[*]
charset = utf-8
indent_style = space
indent_size = 4
insert_final_newline = true
trim_trailing_whitespace = true
end_of_line = auto

commitizen

规范Commit Message提交格式

yarn add commitizen cz-git -D

推荐cz-git

package.json加入commitizen配置

"scripts": {
  "commit": "cz",
},
"config": {
  "commitizen": {
    "path": "node_modules/cz-git"
  }
},

之后git commit可以用yarn commit代替

cz-git还可以自定义配置模板,支持多种文件,推荐搭配commitlintcommitlint.config.js中一同配置,文档有配置案例

husky

git hook工具,可以挂载git钩子常配置pre-commit``commit-msg两个钩子

yarn add husky -D

package.json中添加如下字段,运行可启用git钩子

"scripts": {
  "prepare": "husky install",
},

随后可以通过命令创建钩子命令

npx husky add .husky/pre-commit "npx --no -- lint-staged"

当让也可以自行创建.husky下的钩子文件

echo '
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx --no -- commitlint --edit ${1}
' > .husky/commit-msg

自行创建需要自行执行以下命令使钩子可以执行

chmod a+x .husky/commit-msg

commitlint

校验commit message提交格式

搭配@commitlint/config-conventional使用,也可自行选择合适配置

yarn add @commitlint/cli @commitlint/config-conventional -D

创建commitlint.config.js,这里用例搭配cz-git使用,摘自cz-git文档

// .commitlintrc.js
/** @type {import('cz-git').UserConfig} */
module.exports = {
    ignores: [(commit) => commit.includes('init')],
    extends: ['@commitlint/config-conventional'],
    rules: {
        // @see: https://commitlint.js.org/#/reference-rules
    },
    prompt: {
        alias: { fd: 'docs: fix typos' },
        messages: {
            type: '选择你要提交的类型 :',
            scope: '选择一个提交范围(可选):',
            customScope: '请输入自定义的提交范围 :',
            subject: '填写简短精炼的变更描述 :\n',
            body: '填写更加详细的变更描述(可选)。使用 "|" 换行 :\n',
            breaking: '列举非兼容性重大的变更(可选)。使用 "|" 换行 :\n',
            footerPrefixsSelect: '选择关联issue前缀(可选):',
            customFooterPrefixs: '输入自定义issue前缀 :',
            footer: '列举关联issue (可选) 例如: #31, #I3244 :\n',
            confirmCommit: '是否提交或修改commit ?',
        },
        types: [
            { value: 'feat', name: 'feat:     🚀  新增功能 | A new feature', emoji: '🚀' },
            { value: 'fix', name: 'fix:      🧩  修复缺陷 | A bug fix', emoji: '🧩' },
            { value: 'docs', name: 'docs:     📚  文档更新 | Documentation only changes', emoji: '📚' },
            { value: 'style', name: 'style:    🎨  代码格式 | Changes that do not affect the meaning of the code', emoji: '🎨' },
            { value: 'refactor', name: 'refactor: ♻️   代码重构 | A code change that neither fixes a bug nor adds a feature', emoji: '♻️' },
            { value: 'perf', name: 'perf:     ⚡️  性能提升 | A code change that improves performance', emoji: '⚡️' },
            { value: 'test', name: 'test:     ✅  测试相关 | Adding missing tests or correcting existing tests', emoji: '✅' },
            { value: 'build', name: 'build:    📦️  构建相关 | Changes that affect the build system or external dependencies', emoji: '📦️' },
            { value: 'ci', name: 'ci:       🎡  持续集成 | Changes to our CI configuration files and scripts', emoji: '🎡' },
            { value: 'chore', name: 'chore:    🔨  其他修改 | Other changes that do not modify src or test files', emoji: '🔨' },
            { value: 'revert', name: 'revert:   ⏪️  回退代码 | Revert to a commit', emoji: '⏪️' },
        ],
        useEmoji: true,
        emojiAlign: 'center',
        themeColorCode: '',
        scopes: [],
        allowCustomScopes: true,
        allowEmptyScopes: true,
        customScopesAlign: 'bottom',
        customScopesAlias: 'custom',
        emptyScopesAlias: 'empty',
        upperCaseSubject: false,
        markBreakingChangeMode: false,
        allowBreakingChanges: ['feat', 'fix'],
        breaklineNumber: 100,
        breaklineChar: '|',
        skipQuestions: [],
        issuePrefixs: [
        // 如果使用 gitee 作为开发管理
            { value: 'link', name: 'link:     链接 ISSUES 进行中' },
            { value: 'closed', name: 'closed:   标记 ISSUES 已完成' },
        ],
        customIssuePrefixsAlign: 'top',
        emptyIssuePrefixsAlias: 'skip',
        customIssuePrefixsAlias: 'custom',
        allowCustomIssuePrefixs: true,
        allowEmptyIssuePrefixs: true,
        confirmColorize: true,
        maxHeaderLength: Infinity,
        maxSubjectLength: Infinity,
        minSubjectLength: 0,
        scopeOverrides: undefined,
        defaultBody: '',
        defaultIssues: '',
        defaultScope: '',
        defaultSubject: '',
    },
};

随后注册在.husky/commit-msg钩子中,在git commit时校验commit message

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npx --no -- commitlint --edit "${1}"

lint-staged

指定只检查通过git add添加到暂存区的文件,可以避免每次检查都把整个项目的代码都检查一遍,从而提高效率

yarn add lint-staged -D

创建.lintstagedrc.js

module.exports = {
    "packages/**/*.{js,ts}": ["eslint --fix"]
}

可以运行npx lint-staged检查暂存区文件,--fix会修复错误并自动加入暂存区

随后注册在.husky/pre-commit钩子中,在git commit之前对指定文件运行指定命令

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npx --no -- lint-staged