vue配置stylelint教程

stylelint可以讓css樣式代碼在編輯、保存、提交git的時(shí)候按規(guī)范進(jìn)行檢查及美化,十分好用。

以下以vue項(xiàng)目為例分享一下配置步驟:

1.安裝 stylelint

npm i -D stylelint stylelint-config-stand

如果想使用airbnb的規(guī)范,則后面改為stylelint-config-airbnb。

2.安裝適配預(yù)處理語(yǔ)法的插件

以 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同級(jí)位置

//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層,去掉默認(rèn)的最多2層
    'max-nesting-depth': 20,
    // 顏色值要小寫
    'color-hex-case': 'lower',
    // 顏色值能短則短
    'color-hex-length': 'short',
    // 不能用important
    'declaration-no-important': true,
  },
};
# .stylelintignore
# 舊的不需打包的樣式庫(kù)
*.min.css
?
# 其他類型文件
*.js
*.jpg
*.woff
?
# 測(cè)試和打包目錄
/test/
/dist/
?
# 通過反取忽略目錄
/src/component/*
# 這樣的效果是除 CompA 和 CompB 外其他目錄都會(huì)被忽略

6.安裝vscode的stylelint插件

該插件可以在ide中顯示錯(cuò)誤、修改建議,還能保存時(shí)自動(dòng)美化代碼、修復(fù)可修復(fù)的代碼。

image

7.設(shè)置ide保存時(shí)使用該插件自動(dòng)美化:

MAC的路徑在/Users/用戶名/Library/Application Support/code/User/setting.json

也可以在ide中跳轉(zhuǎn),操作方法如下:

然后添加如下代碼:

{
    "editor.codeActionsOnSave": {
      "source.fixAll.stylelint": true
    }
}

之后在保存時(shí)就會(huì)自動(dòng)美化代碼、修復(fù)可修復(fù)的代碼:

image

8.安裝 webpack 插件

npm i -D stylelint-webpack-plugin

我用的是webpack3.x,如果用最新版的1.2.3會(huì)報(bào)錯(cuò),降為0.10.5后功能正常。

9.添加webpack相關(guān)配置:

在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.可以在命令行運(yùn)行嘗試效果

--fix 表示自動(dòng)修復(fù)能修復(fù)的錯(cuò)誤

npm run lint:css
npm run lint:css --fix
npm run lint:css -- --cache --fix

11.如果想修改樣式規(guī)則,可以在stylelint.config.js中進(jìn)行修改,相關(guān)的配置信息可以在這兒查看

這個(gè)是不完整的中文配置文檔:

以上就是在vue上配置stylelint的過程了,大家也用起來(lái)吧。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容