[Vite] Configure Stylelint(CSS-in-JS) in TypeScript-based React project

2024-04-22 hit count image

Let's see how to add Stylelint to a TypeScript-based React project created using Vite to manage styles (CSS) in the CSS-in-JS environment.

Outline

In this blog post, I will introduce how to add Stylelint to a TypeScript-based React project created using Vite to manage styles (CSS) in the CSS-in-JS environment.

Blog series

This blog post is part of a series. Here is the list of Vite series.

Install Stylelint

Run the following command to install the libraries needed to use Stylelint.

npm i -D stylelint stylelint-config-standard postcss-styled-syntax stylelint-order
# yarn add -D stylelint stylelint-config-standard postcss-styled-syntax stylelint-order
  • stylelint: Install stylelint.
  • stylelint-config-standard: Standard configuration provided by Stylelint.
  • postcss-styled-syntax: Library for checking styles (CSS) in the CSS-in-JS environment.
  • stylelint-order: Library for checking the order of style (CSS) properties.

Configure Stylelint

To use Stylelint, you need to configure Stylelint. Create a .stylelintrc.json file and modify it as follows.

{
  "extends": ["stylelint-config-standard"],
  "customSyntax": "postcss-styled-syntax",
  "plugins": ["stylelint-order"],
  "rules": {
    "order/properties-alphabetical-order": true
  }
}

Execute Stylelint

To use Stylelint, you need to run the command to execute Stylelint. Run the following command to execute Stylelint.

npx stylelint --ignore-path .gitignore '**/*.(css|tsx)

This command runs Stylelint to check if the code follows the basic rules provided by Stylelint. If you want to automatically fix the code according to the rule, run the following command.

npx stylelint --ignore-path .gitignore '**/*.(css|tsx)' --fix

When you run this command, you can see that Stylelint automatically fixes the problems that can be fixed.

To use these commands more easily, open the package.json file and modify it as follows.

...
"scripts": {
  ...
  "lint:css": "stylelint --ignore-path .gitignore '**/*.(css|tsx)'",
  "lint:css:fix": "stylelint --ignore-path .gitignore '**/*.(css|tsx)' --fix"
},
...

Now you can run the following commands to execute Stylelint.

npm run lint:css
npm run lint:css:fix
# yarn lint:css
# yarn lint:css:fix

Completed

Done! We’ve seen how to set up and run Stylelint to manage styles (CSS) in the CSS-in-JS environment in a TypeScript-based React project created using Vite. You can now use Stylelint to check the styles (CSS) and write better code.

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

App promotion

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.

Posts