stylelint 可以让 CSS 样式代码在编辑, 保存, 提交 Git 的时候按规范进行检查及美化, 十分好用.
以下以 vue 项目为例分享一下配置步骤:
1. 安装 stylelint
NPM i -D stylelint stylelint-config-stand
如果想使用 airbnb 的规范, 则后面改为 stylelint-config-airbnb.
2. 安装适配预处理语法的插件
以 Sass 为例:
NPM i -D stylelint-SCSS
3. 安装缺失包
NPM i stylelint-order
4. 编辑 package.JSON
- {
- "scripts": {
- "lint:css": "stylelint **/*.{html,vue,css,sass,scss}"
- },
- "lint-staged": {
- "*.{html,vue,css,sass,scss}": [
- "stylelint --fix",
- "git add"
- ]
- }
- }
5. 添加 stylelint.config.JS 和. stylelintignore 文件, 放到与 package.JSON 同级位置
- //stylelint.config.JS
- module.exports = {
- defaultSeverity: 'error',
- extends: ['stylelint-config-airbnb'],
- plugins: ['stylelint-scss'],
- rules: {
- // 不要使用已被 autoprefixer 支持的浏览器前缀
- 'media-feature-name-no-vendor-prefix': true,
- 'at-rule-no-vendor-prefix': true,
- 'selector-no-vendor-prefix': true,
- 'property-no-vendor-prefix': true,
- 'value-no-vendor-prefix': true,
- // 最多允许嵌套 20 层, 去掉默认的最多 2 层
- 'max-nesting-depth': 20,
- // 颜色值要小写
- 'color-hex-case': 'lower',
- // 颜色值能短则短
- 'color-hex-length': 'short',
- // 不能用 important
- 'declaration-no-important': true,
- },
- };
- # .stylelintignore
- # 旧的不需打包的样式库
- *.min.CSS
- # 其他类型文件
- *.JS
- *.jpg
- *.woff
- # 测试和打包目录
- /test/
- /dist/
- # 通过反取忽略目录
- /src/component/*
- # 这样的效果是除 CompA 和 CompB 外其他目录都会被忽略
6. 安装 vscode 的 stylelint 插件
该插件可以在 ide 中显示错误, 修改建议, 还能保存时自动美化代码, 修复可修复的代码.
image
7. 设置 ide 保存时使用该插件自动美化:
Mac 的路径在 / Users / 用户名 / Library/Application Support/code/User/setting.JSON
也可以在 ide 中跳转, 操作方法如下:
然后添加如下代码:
- {
- "editor.codeActionsOnSave": {
- "source.fixAll.stylelint": true
- }
- }
之后在保存时就会自动美化代码, 修复可修复的代码:
image
8. 安装 webpack 插件
NPM i -D stylelint-webpack-plugin
我用的是 webpack3.x, 如果用最新版的 1.2.3 会报错, 降为 0.10.5 后功能正常.
9. 添加 webpack 相关配置:
在 webpack.conf.JS 中添加如下代码:
- const StylelintPlugin = require('stylelint-webpack-plugin');
- plugins: [
- new StylelintPlugin({
- files: ['**/*.{html,vue,css,sass,scss}'],
- fix: false,
- cache: true,
- failOnError: false
- })
- ]
10. 可以在命令行运行尝试效果
--fix 表示自动修复能修复的错误
- NPM run lint:CSS
- NPM run lint:CSS --fix
- NPM run lint:CSS -- --cache --fix
11. 如果想修改样式规则, 可以在 stylelint.config.JS 中进行修改, 相关的配置信息可以在这儿查看
这个是不完整的中文配置文档:
以上就是在 vue 上配置 stylelint 的过程了, 大家也用起来吧.
来源: http://www.jianshu.com/p/b596f2eb1b41