Eslint + Prettier + stylelint + husky VUE项目配置一篇搞定(简易上手版)

VUE项目格式化配置

前端开发中很多项目都是团队项目,再同时开发中为了避免每个开发者的代码风格样式不同到账项目代码难以琢磨,这时候就格式化就起到了统一的作用。



提示

这里开发工具是使用的 VsCode 各个依赖的版本写在下面。

package.json文件
devDependencies 表示只在开发时用到的依赖
node v16.14.0 (以下依赖安装此版本)

“devDependencies”: {
   	"@commitlint/cli": "^17.6.6",
   	"@commitlint/config-conventional": "^17.6.6",
   	"@vue/cli-plugin-babel": "~4.5.0",
   	"@vue/cli-plugin-eslint": "~4.5.0",
   	"@vue/cli-service": "~4.5.0",
   	"babel-eslint": "^10.1.0",
   	"commitizen": "^4.3.0",
   	"element-ui": "^2.15.12",
   	"eslint": "^6.0.0",
   	"eslint-plugin-vue": "^6.2.2",
   	"husky": "^7.0.4",
   	"install": "^0.13.0",
   	"lint-staged": "12.1.7",
   	"npm": "^9.5.0",
   	"postcss-less": "^6.0.0",
   	"prettier": "^2.8.8",
   	"stylelint": "^14.9.1",
   	"stylelint-config-html": "^1.1.0",
   	"stylelint-config-prettier": "^9.0.3",
   	"stylelint-config-recess-order": "^3.0.0",
   	"stylelint-config-recommended-vue": "^1.4.0",
   	"stylelint-config-standard": "^26.0.0",
   	"stylelint-config-standard-vue": "^1.0.0",
   	"stylelint-less": "^1.0.6",
   	"stylelint-order": "^5.0.0",
}

提示:以下是本篇文章正文内容,下面案例可供参考

一、eslint 配置

1.安装

npm install eslint@6.0.0 --save-dev
根目录下创建 .eslintrc.js 和 .eslintignore 两个文件

2.配置

.eslintrc.js: eslint配置文件
eslint中文地址

module.exports = {
  root: true, // 当前项目使用这个配置文件, 不会往父级目录找.eslintrc.js文件
  env: { // 指定eslint启动环境(vuecli底层是node支持), browser: true也可以在浏览器设置
    node: true
  },
  extends: [ // 扩展配置
    'plugin:vue/essential', // vue里必须的规则
    '@vue/standard' // 使eslint继承@vue/cli脚手架里的 - standard标准
  ],
  parserOptions: { // 对新语法使用eslint
    parser: 'babel-eslint' // 使用babel-eslint 来解析新语法ES6
  },
  // 这里可以进行自定义规则配置
  // key:规则代号
  // value:具体的限定方式
  // "off" or 0 - 关闭规则
  // "warn" or 1 - 将规则视为一个警告(不会影响退出码),只警告,不会退出程序
  // "error" or 2 - 将规则视为一个错误 (退出码为1),报错并退出程序
  // 自定义规则 - 其实上面集成后有很多内置的规则, 这里可以进行规则的一些修改
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off', // 上线环境用打印就报警告, 开发环境关闭此规则
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off', // debugger可以终止代码执行
    'no-multiple-empty-lines': 'off' // 不允许有连续多行空行(关闭规则)
  }
}

.eslintignore: 配置被 eslint 检查忽略的文件(根据自己的项目指定目录或者文件)

node_modules
dist

3.执行

在 package.json 中配置单独执行格式化
“lint:eslint”: 自定义命令名称
–ext .vue,.js,.ts,.tsx ./src 指定检查需要格式化的文件

"script": {
	"lint:eslint": "eslint --fix --ext .vue,.js,.ts,.tsx ./src",
}

配置好后当前终端下输入 npm run lint:eslint 或者 yarn lint:eslint 即可执行格式化

二、Prettier 配置

1.安装

npm install prettier@6.0.0 --save-dev
根目录下创建 .prettierrc.js 和 .prettierrcignore 两个文件

2.配置

.prettierrc.js: prettier 配置文件
prettier规则地址

module.exports = {
	printWidth: 150, // 超过最大值换行
	tabWidth: 4, // 缩进字节数
	useTabs: true, // 使用制表符而不是空格缩进行
	singleQuote: false, // 使用单引号(true, false双引号)
	quoteProps: "as-needed", // 更改引用对象属性的时间 可选值"<as-needed|consistent|preserve>"
	bracketSpacing: true, // 在对象, 数组括号与文字之间加空格"{ foo: bar }"
	trailingComma: "none", // 多行时尽可能打印尾随逗号。(例如,单行数组永远不会出现逗号结尾。) 可选值"<none|es5|all>",默认none
	jsxSingleQuote: false, // 在JSX中使用单引号而不是双引号
	arrowParens: "always", //(params) => {} 箭头函数参数只有一个时是否要有小括号。avoid:省略括号,always:不省略括号
	insertPragma: false, // 如果文件顶部已经有一个doclock,这个选项将新建一行注释,并打上@format标识
	requirePragma: false, // 指定要使用的解析器,不需要斜纹开头的@prettier
	proseWrap: "preserve", // 默认值。因为使用了一些折行敏感型的渲染器(如GitHub comment)而按照markdown文本样式进行折行
	endOfLine: "auto", // 换行符使用 lf 结尾是 可选值"<auto|lf|crlf|cr>"
	rangeStart: 0, // 这两个选项可用于格式化以给定字符偏移量(分别包括和不包括)开始和结束的代码
	rangeEnd: Infinity,
	vueIndentScriptAndStyle: false, // Vue文件脚本和样式标签缩进
	endOfLine: "auto"
};

.prettierrcignore: 配置被 prettierrc 检查忽略的文件(根据自己的项目指定目录或者文件)

/dist/*
.local
/node_modules/*

**/*.svg
**/*.sh
**/*.less
/public/*

3.执行

在 package.json 中配置单独执行格式化
“lint:prettier”: 自定义命令名称
–loglevel warn "src/**/*.{js,ts,json,tsx,css,less,scss,html,md} 指定检查需要格式化的文件
npx prettier --write . 格式化所有除 .prettierrcignore 标明之外的文件

"script": {
	"lint:prettier": "prettier --write .",
}

配置好后当前终端下输入 npm run lint:prettier 或者 yarn lint:perttier 即可执行格式化

三、stylelint 配置

1.安装

npm install stylelint@14.9.1 --save-dev
根目录下创建 .stylelint.js 和 .stylelintignore 两个文件
另外再多装几个拓展插件
stylelint-config-standard: stylelint-config-standard是stylelint的推荐配置
stylelint-config-prettier: 配置 prettier 和 stylelint 兼容
stylelint-config-recess-order: 配置stylelint css属性书写顺序插件,
stylelint-order: CSS属性排序插件
postcss-html: 这里我用的是 vue + less 所以用 postcss-html 和 postcss-less
postcss-less

npm install stylelint-config-standard stylelint-config-prettier stylelint-config-recess-order stylelint-order postcss-html postcss-less --save-dev 

2.配置

.stylelint.js: stylelint 配置文件

module.exports = {
	extends: [
		"stylelint-config-standard", // 配置stylelint拓展插件
		"stylelint-config-prettier", // 配置stylelint和prettier兼容
		"stylelint-config-recess-order" // 配置stylelint css属性书写顺序插件,
	],
	plugins: ["stylelint-order"],
	overrides: [
		{
			files: ["**/*.vue"],
			customSyntax: "postcss-html"
		},
		{
			files: ["**/*.less"],
			customSyntax: "postcss-less"
		}
	],
	ignoreFiles: ["**/*.js", "**/*.jsx", "**/*.tsx", "**/*.ts", "**/*.json"], // 忽略检查指定文件
	rules: {
		indentation: null, // 指定缩进空格
		"no-descending-specificity": null, // 禁止在具有较高优先级的选择器后出现被其覆盖的较低优先级的选择器
		"function-url-quotes": "always", // 要求或禁止 URL 的引号 "always(必须加上引号)"|"never(没有引号)"
		"string-quotes": "double", // 指定字符串使用单引号或双引号
		"unit-case": null, // 指定单位的大小写 "lower(全小写)"|"upper(全大写)"
		"color-hex-case": "lower", // 指定 16 进制颜色的大小写 "lower(全小写)"|"upper(全大写)"
		"color-hex-length": "long", // 指定 16 进制颜色的简写或扩写 "short(16进制简写)"|"long(16进制扩写)"
		"rule-empty-line-before": "never", // 要求或禁止在规则之前的空行 "always(规则之前必须始终有一个空行)"|"never(规则前绝不能有空行)"|"always-multi-line(多行规则之前必须始终有一个空行)"|"never-multi-line(多行规则之前绝不能有空行。)"
		"font-family-no-missing-generic-family-keyword": null, // 禁止在字体族名称列表中缺少通用字体族关键字
		"block-opening-brace-space-before": "always", // 要求在块的开大括号之前必须有一个空格或不能有空白符 "always(大括号前必须始终有一个空格)"|"never(左大括号之前绝不能有空格)"|"always-single-line(在单行块中的左大括号之前必须始终有一个空格)"|"never-single-line(在单行块中的左大括号之前绝不能有空格)"|"always-multi-line(在多行块中,左大括号之前必须始终有一个空格)"|"never-multi-line(多行块中的左大括号之前绝不能有空格)"
		"property-no-unknown": null, // 禁止未知的属性(true 为不允许)
		"no-empty-source": null, // 禁止空源码
		"declaration-block-trailing-semicolon": null, // 要求或不允许在声明块中使用尾随分号 string:"always(必须始终有一个尾随分号)"|"never(不得有尾随分号)"
		"selector-class-pattern": null, // 强制选择器类名的格式
		"value-no-vendor-prefix": null, // 关闭 vendor-prefix(为了解决多行省略 -webkit-box)
		"at-rule-no-unknown": null,
		"selector-pseudo-class-no-unknown": [
			true,
			{
				ignorePseudoClasses: ["global", "v-deep", "deep"]
			}
		],
		"order/properties-order": [
			"position",
			"top",
			"right",
			"bottom",
			"left",
			"z-index",
			"display",
			"justify-content",
			"align-items",
			"float",
			"clear",
			"overflow",
			"overflow-x",
			"overflow-y",
			"margin",
			"margin-top",
			"margin-right",
			"margin-bottom",
			"margin-left",
			"padding",
			"padding-top",
			"padding-right",
			"padding-bottom",
			"padding-left",
			"width",
			"min-width",
			"max-width",
			"height",
			"min-height",
			"max-height",
			"font-size",
			"font-family",
			"font-weight",
			"border",
			"border-style",
			"border-width",
			"border-color",
			"border-top",
			"border-top-style",
			"border-top-width",
			"border-top-color",
			"border-right",
			"border-right-style",
			"border-right-width",
			"border-right-color",
			"border-bottom",
			"border-bottom-style",
			"border-bottom-width",
			"border-bottom-color",
			"border-left",
			"border-left-style",
			"border-left-width",
			"border-left-color",
			"border-radius",
			"text-align",
			"text-justify",
			"text-indent",
			"text-overflow",
			"text-decoration",
			"white-space",
			"color",
			"background",
			"background-position",
			"background-repeat",
			"background-size",
			"background-color",
			"background-clip",
			"opacity",
			"filter",
			"list-style",
			"outline",
			"visibility",
			"box-shadow",
			"text-shadow",
			"resize",
			"transition"
		]
	}
};

.stylelintignore: 配置被 stylelint 检查忽略的文件(根据自己的项目指定目录或者文件)

/node_modules/
/dist/*
/public/*
*.min.css
*.js
*.jpg
*.png
*.eot
*.ttf
*.woff
*.json

3.执行

在 package.json 中配置单独执行格式化
“lint:prettier”: 自定义命令名称
src/**/*.{vue,scss,css,sass,less} --fix 指定检查需要格式化的文件

"script": {
	"lint:stylelint": "stylelint src/**/*.{vue,scss,css,sass,less} --fix",
}

配置好后当前终端下输入 npm run lint:stylelint 或者 yarn lint:stylelint 即可执行格式化


四.lint-staged配置

lint-staged:是一个过滤器一般会配合husky使用,可以对本次修改过的代码,再commit之前进行一些列的格式化,一次性对本次的修改文件执行 eslint + prettier + stylelint 格式化

1.安装

npm install lint-staged@12.1.7 --save-dev
根目录下创建 .lintstagedrc.js

2.配置

.lintstagedrc.js
“*.{js,jsx,ts,tsx}”: [“eslint --fix”, “prettier --write”]对不同类型的文件指定使用哪种方式进行格式化

module.exports = {
	"*.{js,jsx,ts,tsx}": ["eslint --fix", "prettier --write"],
	"{!(package)*.json,*.code-snippets,.!(browserslist)*rc}": ["prettier --write--parser json"],
	"package.json": ["prettier --write"],
	"*.vue": ["eslint --fix", "prettier --write", "stylelint --fix"],
	"*.{scss,less,styl,html}": ["stylelint --fix", "prettier --write"],
	"*.md": ["prettier --write"]
};

3.执行

在 package.json 中配置单独执行格式化
“lint:lint-staged”: 自定义命令名称

"script": {
	"lint:lint-staged": "lint-staged",
}

配置好后当前终端下输入 npm run lint:lint-staged 或者 yarn lint:lint-staged 即可执行格式化

五.husky配置

husky就是Git 中的钩子,较常用的有 pre-push、pre-commit ,其中 pre-commit 钩子会在 commit 前触发,pre-push 会在 push 前触发

1.安装

npm install husky@7.0.4 --save-dev

2.执行

终端执行 npx husky install 根目录下就会创建一个.husky 的文件
或者把它配置到 package 中

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

执行 npm run prepare 效果是一样的

执行以下命令,在husky文件夹下自动生成pre-commit文件

npx husky add .husky/pre-commit "npm run lint:lint-staged"

执行以下命令,在husky文件夹下自动生成 commit-msg文件

npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'

六.commitlint + commitizen提交规范化配置

commitlint插件包是在运行 git commmit -m ‘message’ 时检查 message 是否是提前设置好的提交格式的工具,目的是制定提交规范。
commitizen插件包 自定义 自动化提示工具

1.安装

npm install @commitlint/config-conventional @commitlint/cli --save-dev
npm install commitizen --save-dev

2.配置

再更目录下创建配置文件commitlint.config.js 或者 .commitlintrc.js
ruls 规范参考 commitlint

package.json 增加 config 配置

"config": {
	"commitizen": {
		"path": "node_modules/cz-conventional-changelog"
	}
}

.commitlint.config.js

module.exports = {
	ignores: [(commit) => commit.includes("init")],
	extends: ["@commitlint/config-conventional"],
	rules: {
		// @see: https://commitlint.js.org/#/reference-rules
		"body-leading-blank": [2, "always"],
		"footer-leading-blank": [1, "always"],
		"header-max-length": [2, "always", 108],
		"subject-empty": [2, "never"],
		"type-empty": [2, "never"],
		"subject-case": [0],
		"type-enum": [
			2,
			"always",
			["feat", "fix", "docs", "style", "refactor", "perf", "test", "build", "ci", "chore", "revert", "wip", "workflow", "types", "release"]
		]
	},
	prompt: {
		messages: {
			type: "Select the type of change that you're committing:",
			scope: "Denote the SCOPE of this change (optional):",
			customScope: "Denote the SCOPE of this change:",
			subject: "Write a SHORT, IMPERATIVE tense description of the change:\n",
			body: 'Provide a LONGER description of the change (optional). Use "|" to break new line:\n',
			breaking: 'List any BREAKING CHANGES (optional). Use "|" to break new line:\n',
			footerPrefixsSelect: "Select the ISSUES type of changeList by this change (optional):",
			customFooterPrefixs: "Input ISSUES prefix:",
			footer: "List any ISSUES by this change. E.g.: #31, #34:\n",
			confirmCommit: "Are you sure you want to proceed with the commit above?"
			// 中文版
			// 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 don't modify src or test files",
				emoji: "🔨"
			},
			{
				value: "revert",
				name: "revert:   ⏪️  Reverts a previous commit",
				emoji: "⏪️"
			}
			// 中文版
			// { value: "特性", name: "特性:   🚀  新增功能", emoji: "🚀" },
			// { value: "修复", name: "修复:   🧩  修复缺陷", emoji: "🧩" },
			// { value: "文档", name: "文档:   📚  文档变更", emoji: "📚" },
			// { value: "格式", name: "格式:   🎨  代码格式(不影响功能,例如空格、分号等格式修正)", emoji: "🎨" },
			// { value: "重构", name: "重构:   ♻️  代码重构(不包括 bug 修复、功能新增)", emoji: "♻️" },
			// { value: "性能", name: "性能:   ⚡️  性能优化", emoji: "⚡️" },
			// { value: "测试", name: "测试:   ✅  添加疏漏测试或已有测试改动", emoji: "✅" },
			// { value: "构建", name: "构建:   📦️  构建流程、外部依赖变更(如升级 npm 包、修改 webpack 配置等)", emoji: "📦️" },
			// { value: "集成", name: "集成:   🎡  修改 CI 配置、脚本", emoji: "🎡" },
			// { value: "回退", name: "回退:   ⏪️  回滚 commit", emoji: "⏪️" },
			// { value: "其他", name: "其他:   🔨  对构建过程或辅助工具和库的更改(不影响源文件、测试用例)", emoji: "🔨" }
		],
		useEmoji: true,
		themeColorCode: "",
		scopes: [],
		allowCustomScopes: true,
		allowEmptyScopes: true,
		customScopesAlign: "bottom",
		customScopesAlias: "custom",
		emptyScopesAlias: "empty",
		upperCaseSubject: false,
		allowBreakingChanges: ["feat", "fix"],
		breaklineNumber: 100,
		breaklineChar: "|",
		skipQuestions: [],
		issuePrefixs: [{ value: "closed", name: "closed:   ISSUES has been processed" }],
		customIssuePrefixsAlign: "top",
		emptyIssuePrefixsAlias: "skip",
		customIssuePrefixsAlias: "custom",
		allowCustomIssuePrefixs: true,
		allowEmptyIssuePrefixs: true,
		confirmColorize: true,
		maxHeaderLength: Infinity,
		maxSubjectLength: Infinity,
		minSubjectLength: 0,
		scopeOverrides: undefined,
		defaultBody: "",
		defaultIssues: "",
		defaultScope: "",
		defaultSubject: ""
	}
};

3.执行

在 package.json 中配置单独执行格式化
“commit”: 自定义命令名称

"script": {
	"commit": "git pull && git add -A && git-cz && git push",
}

配置好后当前终端下输入 npm commit 或者 yarn commit 按照commitizen规定好的格式填写后即可提交代码

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值