Search code examples
cssvue.jssassstylelint

How to run stylelint on the style tag written inside a Vue file


I'm configuring the stylelints for the styles in my Vue project. For the independent .css and .scss files, I did this using stylelint-scss package. But I'm facing difficulty to configure this for the style tags written inside my vue component like below.

<script setup lang="ts">
defineProps({})
</script>

<template class="container">
  <p>Sample p tag</p>
</template>

<style lang="scss" scoped>
.container {
  p {
    color: white;
  }
  @media (min-width: 500px) {  // Prohibited as per scss/media-feature-value-dollar-variable rule
    color: green;
  }
}
</style>

I have to run stylelint for the styles written inside <style lang="scss" scoped></style> tag


Solution

  • To lint CSS, SCSS and SCSS within Vue SFCs, you can use Stylelint's overrides configuration property to extend a combination of shared configs:

    First, install the dependencies:

    npm i --save-dev postcss-html stylelint-config-standard-vue stylelint-config-standard stylelint-config-standard-scss
    

    Then update your Stylelint configuration to:

    {
      "extends": ["stylelint-config-standard"],
      "overrides": [
        {
          "files": ["*.scss", "**/*.scss"],
          "extends": ["stylelint-config-standard-scss"]
        },
        {
          "files": ["*.vue", "**/*.vue"],
          "extends": [
            "stylelint-config-standard-scss",
            "stylelint-config-standard-vue/scss"
          ]
        }
      ]
    }
    

    Finally, run Stylelint on your CSS, SCSS and Vue files:

    npx stylelint "**/*.{css,scss,vue}"
    

    This configuration tells Stylelint to use the official config for CSS files, the SCSS community config for SCSS files and both the SCSS and Vue community configs for SCSS within Vue files.

    For the independent .css and .scss files, did this using stylelint-scss package

    The stylelint-config-standard-scss shared config bundles the stylelint-scss plugin pack for you, so you don't need to include it in your configuration.

    Each community config also bundles the relevant custom syntax for each language or container: postcss-scss and postcss-html for SCSS and Vue files, respectively.