@fespec/stylelint-config
v2.1.0
Published
前端工程化规范CLI工具 - stylelint配置
Downloads
9
Maintainers
Readme
@fespec/stylelint-config
前端工程化规范CLI工具 - stylelint配置
简介
本包提供了前端工程化规范中的stylelint配置,用于统一项目中的CSS/SCSS代码风格,确保代码质量和一致性。
安装
# 使用npm
npm install --save-dev @fespec/stylelint-config stylelint stylelint-scss
# 使用yarn
yarn add --dev @fespec/stylelint-config stylelint stylelint-scss
# 使用pnpm
pnpm add --save-dev @fespec/stylelint-config stylelint stylelint-scss使用方法
在项目根目录下创建.stylelintrc.js文件,添加以下内容:
module.exports = {
extends: "@fespec/stylelint-config",
};或者在package.json中添加:
{
"stylelint": {
"extends": "@fespec/stylelint-config"
}
}规则说明
本配置基于stylelint官方推荐规则,并结合前端工程化最佳实践进行了优化,主要包括以下几类规则:
1. 可能的错误检测
block-no-empty允许空的代码块color-no-invalid-hex禁止无效的十六进制颜色comment-no-empty禁止空的注释declaration-block-no-duplicate-properties禁止声明块中的重复属性font-family-no-duplicate-names禁止字体族名称重复function-calc-no-unspaced-operator禁止calc函数中操作符两边没有空格media-feature-name-no-unknown禁止未知的媒体特性名称no-empty-source允许空的源no-extra-semicolons禁止多余的分号property-no-unknown禁止未知的属性selector-pseudo-class-no-unknown禁止未知的伪类选择器selector-pseudo-element-no-unknown禁止未知的伪元素选择器string-no-newline禁止字符串中包含换行符unit-no-unknown禁止未知的单位
2. 风格问题
indentation缩进使用2个空格block-closing-brace-newline-before多行块关闭大括号前必须换行block-closing-brace-space-before单行块关闭大括号前必须有空格block-opening-brace-newline-after多行块打开大括号后必须换行block-opening-brace-space-before块打开大括号前必须有空格block-opening-brace-space-after单行块打开大括号后必须有空格color-hex-case颜色十六进制值使用小写color-hex-length颜色十六进制值使用简写形式comment-whitespace-inside注释内必须有空格declaration-colon-space-before声明冒号前不能有空格declaration-colon-space-after声明冒号后必须有空格declaration-block-single-line-max-declarations单行声明块最多只能有一个声明declaration-block-trailing-semicolon声明块必须有尾随分号length-zero-no-unit长度为零时不使用单位max-line-length最大行长度为100selector-max-id选择器中id选择器的最大数量为0value-list-comma-space-after单行值列表中逗号后必须有空格
3. SCSS规则
scss/at-rule-no-unknown禁止未知的SCSS at-rulescss/double-slash-comment-whitespace-insideSCSS双斜杠注释内必须有空格
在package.json中添加脚本
为了方便使用,可以在项目的package.json中添加以下脚本:
{
"scripts": {
"lint:css": "stylelint \"**/*.{css,scss,sass,less}\"",
"lint:css:fix": "stylelint \"**/*.{css,scss,sass,less}\" --fix"
}
}然后可以使用以下命令进行代码检查和自动修复:
# 检查CSS/SCSS文件
npm run lint:css
# 自动修复CSS/SCSS文件中的问题
npm run lint:css:fix在IDE中集成
VS Code
- 安装 Stylelint 插件
- 在VS Code的设置中添加以下配置:
{
"editor.codeActionsOnSave": {
"source.fixAll.stylelint": true
},
"stylelint.validate": ["css", "scss", "sass", "less"]
}WebStorm
- 在设置中启用Stylelint:
Settings -> Languages & Frameworks -> Style Sheets -> Stylelint - 勾选"Enable"选项
- 选择Stylelint包的路径
测试
本配置包包含了完整的测试用例,可以通过以下命令运行测试:
# 安装依赖
npm install
# 运行所有测试
npm test
# 监视模式运行测试
npm run test:watch
# 生成测试覆盖率报告
npm test -- --coverage测试文件位于__tests__目录下,包括:
stylelint-config.test.js: 测试配置对象的完整性和正确性index.css: 符合所有规则的有效CSS文件essential.css: 包含一些规则违反的无效CSS文件sass-test.scss: 用于测试SCSS规则的文件
