配置 stylelint
stylelint 为 css 的 lint 工具。可格式化 css 代码,检查 css 语法错误与不合理的写法,指定 css 书写顺序等。
以下使用 scss 作为预处理器为例,安装以下依赖:
pnpm add sass sass-loader stylelint postcss postcss-scss postcss-html stylelint-config-prettier stylelint-config-recess-order stylelint-config-recommended-scss stylelint-config-standard stylelint-config-standard-vue stylelint-scss stylelint-order stylelint-config-standard-scss -D
3.1.stylelintrc.cjs
配置文件
官网:https://stylelint.bootcss.com/
// @see https://stylelint.bootcss.com/module.exports = {extends: ['stylelint-config-standard', // 配置stylelint拓展插件'stylelint-config-html/vue', // 配置 vue 中 template 样式格式化'stylelint-config-standard-scss', // 配置stylelint scss插件'stylelint-config-recommended-vue/scss', // 配置 vue 中 scss 样式格式化'stylelint-config-recess-order', // 配置stylelint css属性书写顺序插件,'stylelint-config-prettier', // 配置stylelint和prettier兼容],overrides: [{files: ['**/*.(scss|css|vue|html)'],customSyntax: 'postcss-scss',},{files: ['**/*.(html|vue)'],customSyntax: 'postcss-html',},],ignoreFiles: ['**/*.js','**/*.jsx','**/*.tsx','**/*.ts','**/*.json','**/*.md','**/*.yaml',],/*** null => 关闭该规则* always => 必须*/rules: {'value-keyword-case': null, // 在 css 中使用 v-bind,不报错'no-descending-specificity': null, // 禁止在具有较高优先级的选择器后出现被其覆盖的较低优先级的选择器'function-url-quotes': 'always', // 要求或禁止 URL 的引号 "always(必须加上引号)"|"never(没有引号)"'no-empty-source': null, // 关闭禁止空源码'selector-class-pattern': null, // 关闭强制选择器类名的格式'property-no-unknown': null, // 禁止未知的属性(true 为不允许)'block-opening-brace-space-before': 'always', //大括号之前必须有一个空格或不能有空白符'value-no-vendor-prefix': null, // 关闭 属性值前缀 --webkit-box'property-no-vendor-prefix': null, // 关闭 属性前缀 -webkit-mask'selector-pseudo-class-no-unknown': [// 不允许未知的选择器true,{ignorePseudoClasses: ['global', 'v-deep', 'deep'], // 忽略属性,修改element默认样式的时候能使用到},],},
}
3.2 stylelintignore忽略文件
/node_modules/*
/dist/*
/html/*
/public/*
3.3 运行脚本
"scripts": {"lint:style": "stylelint src/**/*.{css,scss,vue} --cache --fix"
}
最后配置统一的 prettier 来格式化我们的 js 和 css,html 代码:
"scripts": {"dev": "vite --open","build": "vue-tsc && vite build","preview": "vite preview","lint": "eslint src","fix": "eslint src --fix","format": "prettier --write \"./**/*.{html,vue,ts,js,json,md}\"","lint:eslint": "eslint src/**/*.{ts,vue} --cache --fix","lint:style": "stylelint src/**/*.{css,scss,vue} --cache --fix"},
当我们运行pnpm run format
的时候,会把代码直接格式化。