Adding Super Custom Style-Lint Rules for Styled-Components πŸš€

Adding Super Custom Style-Lint Rules for Styled-Components πŸš€

Β·

3 min read

By SrinivasTheDeveloper, 26th October 2023

Hey there, young web developer! Today, we're going on an exciting journey to learn how to add custom StyleLint rules to our styled components. Think of it as giving your superhero a brand new power! πŸ¦Έβ€β™€οΈ

Why Do We Need Custom StyleLint Rules?

Just like superheroes have unique powers, your projects can have specific style requirements. By adding custom StyleLint rules, you can make sure your styles follow these rules.

For example, we'll create a rule to replace hard-coded colours with variables. This makes your styles more flexible and easier to maintain.

Installation - Let's Get the Tools!

Before we start, we need to install StyleLint and a few extra tools:

  • stylelint: Our superhero tool.

  • stylelint-processor-styled-components: It helps StyleLint understand styled-components.

  • stylelint-config-recommended: This is a basic set of rules.

  • stylelint-custom-processor-loader: It's like a booster for our superhero. It helps Webpack understand our custom rules.

Let's install these tools:

npm install --save-dev \
  stylelint \
  stylelint-processor-styled-components \
  stylelint-config-recommended \
  stylelint-custom-processor-loader

Creating a Custom StyleLint Configuration

Our superhero, StyleLint, needs a set of rules to follow. We'll create a .stylelintrc file in the main folder of our project:

File: .stylelintrc

{
  "processors": [
    "stylelint-processor-styled-components"
  ],
  "extends": [
    "stylelint-config-recommended"
  ],
  "rules": {
    // Your custom rules go here
    "my-custom-rule": true
  }
}

Creating Custom Rules

Now, let's create a custom rule. We want to replace hard-coded colours with variables. It's like replacing a mystery potion with a known ingredient.

File: .stylelintrc

{
  "processors": [
    "stylelint-processor-styled-components"
  ],
  "extends": [
    "stylelint-config-recommended"
  ],
  "rules": {
    "my-custom-rule": true,
    // Step 1: Create the rule
    "styled-components/single-interpolation-per-line": true,
    "selector-max-id": 0,
    "no-descending-specificity": null,
    "string-quotes": "double",
    "property-no-unknown": [
      true,
      {
        "ignoreProperties": ["composes"]
      }
    ],
    // Step 2: Define your custom rule
    "my-custom-rule": [
      true,
      {
        "message": "Use color variables instead of hard-coded colors"
      }
    ],
    // Step 3: Implement your custom rule
    "color-no-invalid-hex": true,
    "color-hex-case": "lower",
    "color-hex-length": "short",
    "no-eol-whitespace": true,
    "declaration-empty-line-before": "never",
    "declaration-block-no-duplicate-properties": true,
    "block-opening-brace-newline-after": "always",
    "selector-pseudo-element-no-unknown": [
      true,
      {
        "ignorePseudoElements": ["v-deep"]
      }
    ],
    "selector-type-no-unknown": [
      true,
      {
        "ignore": ["custom-elements"]
      }
    ],
    "selector-pseudo-class-parentheses-space-inside": "never"
  }
}

Super Custom Rule: Replacing Hard-Coded Colors

Our custom rule "my-custom-rule" will replace hard-coded colours with variables. Here's how we do it:

File: my-custom-stylelint-rules.js

module.exports = {
  // Step 4: Implement your custom rule logic
  "my-custom-rule": function (enabled, options, context) {
    return function (root, result) {
      const validOptions = stylelint.utils.validateOptions(
        result,
        "my-custom-rule",
        {
          actual: enabled,
          possible: [true],
        }
      );

      if (!validOptions) {
        return;
      }

      // Step 5: Create a function to check and fix your custom rule
      root.walkDecls(decl => {
        // If a declaration includes a hex color code ie. #FAbd12
        if (decl.prop.includes("color") && decl.value.match(/^#[0-9A-Fa-f]+$/)) {
          const message = options.message || "Use color variables instead of hard-coded colors";
          stylelint.utils.report({
            message: message,
            node: decl,
            result: result,
            ruleName: "my-custom-rule",
          });
        }
      });
    };
  }
};

Run the Custom Rule

Now that you've created your super custom rule, it's

time to put it into action. Run the linting process, and your superhero, StyleLint, will check your styles according to your custom rules:

npm run lint:css

Congratulations!

You've just given your superhero, StyleLint, an amazing new power by adding custom rules. This makes your projects more organized and easier to maintain. Plus, you've created a special rule to replace hard-coded colours with variables, making your styles super flexible! 🌟

Now, go out there and create beautifully styled components with confidence. You're on your way to becoming a style superhero! πŸ’ƒπŸ’»πŸŽ¨

Remember: Just like superheroes save the day, your custom rules save your project from style chaos. πŸ¦Ήβ€β™€οΈ

Β