vue3配置stylelint

发布时间 2023-06-07 09:53:11作者: 游戏三昧的木笔

  stylelint为css的lint工具,可格式化css代码,检查css语法错误与不合理的写法,指定css书写顺序等。
  以scss作为预处理器为例,看如何配置stylelint
1. 安装以下依赖

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

2. 新建.stylelintrc.cjs配置文件
官网: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(必须加上引号)
    "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"] // 忽略属性,修改
      }
    ]
  }
};

3. 新建.stylelintignore忽略文件
文件的内容表示不需对这些文件进行校验

/node_modules/*
/dist/*
/html/*
/public/*

4. package.json中的scripts中加入

"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"

5. 可以在.vue文件上写一些东西,如

<template>
  <div class="box">
    <h1>App根组件</h1>
  </div>
</template>

<script setup lang="ts">
const str = "你好!";
</script>
<style scoped lang="scss">
.box{
  width: 600px;
  height: 400px;
  background: black;
  h1{
    color: white;
    
  }
}
</style>

6.然后在控制台pnpm run format即可