[Code Quality] Stylelint V14

2023-10-08 hit count image

Let's see how to install and configure Stylelint to check code style of CSS, SCSS files, and CSS-in-JS.

This blog post is about the V14 version of Stylelint. If you want to know how to install an configure about the V15 version of Stylelint, please see the following link.

Outline

When we develop the website, we use CSS(Cascading Style Sheets) for the style of the website. In this blog post, I will introduce how to install and configure Stylelint to check code style of CSS, SCSS files, and CSS-in-JS.

You can see the full source code of this blog post on the following link.

Install Node

To use the Stylelint, you need to install Node. Install Node for your system by following.

macOS

Homebrew is a package manager for macOS to install and manage packages. You can simple install packages with Homebrew. Execute the command below to install Homebrew.

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

After installing, execute the following command to check Homebrew installed well.

brew --version

If the version is now shown up, exit Termital and restart it. If you already installed Homebrew, you can skip this step. Next, execute the command below to install Node.

brew install node

Windows

In Windows, Chocolatey is a package manager. Open the CMD or Powershell with Administrator privileges. Execute the command below to install Chocolatey.

Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

After installing, execute the following command to check Chocolatey installed well.

choco –version

If the version of Chocolatey is not shown up, exit CMD or Powershell and restart it. After installing Chocolatey, execute the command below to install Node.

choco install -y nodejs.install

Stylelint for CSS

Let’s see how to install and configure Stylelint to check the CSS files.

Create package.json for Stylelint for CSS

The Stylelint works on the Node development environment. So, we need to create the package.json file to manage the Node packages. Execute the following command to create the package.json file.

npm init

After executing the command, you can see the many questions. If you don’t need to change the default value, just press Enter key for all of them.

package name: (stylelint-example)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)

After that, you can see the package.json file created like the below.

{
  "name": "stylelint-example",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Install Stylelint for CSS

If you want to use Stylelint to check the CSS files, execute the command below to install Stylelint and required libraries.

npm install --save-dev stylelint stylelint-config-standard stylelint-config-prettier

Configure Stylelint for CSS

To use Stylelint, you need to create the .stylelintrc.json file and modify it like the below.

{
  "extends": ["stylelint-config-standard", "stylelint-config-prettier"]
}

Stylelint execution script for CSS

To use Stylelint for checkint all CSS files, modify the package.json file like the below.

{
  ...
  "scripts": {
    "lint:css": "stylelint --ignore-path .gitignore '**/*.css'",
  },
  ...
}

we set .gitignore to the --ignore-path option not to check unnecessary files.

Execute Stylelint for CSS

To check Stylelint works well, create the test.css file and modify it like the below.

h2 {
  margin: 0 0 1rem 0;
  font-size: 1.5rem;
}

And then, execute the following command to check Stylelint works well.

npm run lint:css

If you install and configure Stylelint well, you can see the following warning message.

test.css
 2:3  ✖  Unexpected longhand value '0 0 1rem 0' instead of '0 0 1rem'  shorthand-property-no-redundant-values

After modifying the test.css file like the below and executing Stylelint, you can see the issue fixed.

h2 {
  margin: 0 0 1rem;
  font-size: 1.5rem;
}

Stylelint for SCSS

Let’s see how to install and configure Stylelint to check the SCSS files,

Create package.json for Stylelint for SCSS

Stylelint works on the Node development environment. So, we need to create the package.json file to manage the Node packages. Execute the following command to create the package.json file.

npm init

After executing the command, you can see the many questions. If you don’t need to change the default value, just press Enter key for all of them.

package name: (stylelint-example)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)

After that, you can see the package.json file created like the below.

{
  "name": "stylelint-example",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Install Stylelint for SCSS

To check the SCSS files by Stylelint, execute the command below to install Stylelint and required libraries.

npm install --save-dev stylelint stylelint-config-standard-scss stylelint-config-prettier-scss

Configure Stylelint for SCSS

To use Stylelin, you need to create the .stylelintrc.json file and modify it like the below.

{
  "extends": ["stylelint-config-standard-scss", "stylelint-config-prettier-scss"]
}

Stylelint execution script for SCSS

To check SCSS files by Stylelint, modify the package.json file like the below.

{
  ...
  "scripts": {
    "lint:css": "stylelint --ignore-path .gitignore '**/*.scss'",
  },
  ...
}

we set .gitignore to the --ignore-path option not to check unnecessary files.

Execute Stylelint for SCSS

Next, to check Stylelint works well, create the test.scss file and modify it like the below.

$font-stack: Helvetica, sans-serif;
$primary-color: #333;

body {
  font: 100% $font-stack;
  color: $primary-color;
}

And then, execute the following command to check Stylelint works well.

npm run lint:css

If you install and configure Stylelint well, you can see the following warning message.

test.scss
 1:14  ✖  Expected "Helvetica" to be "helvetica"  value-keyword-case

After modifying the test.scss file like the below and executing Stylelint, you can see the issue fixed.

$font-stack: helvetica, sans-serif;
$primary-color: #333;

body {
  font: 100% $font-stack;
  color: $primary-color;
}

Stylelint for CSS-in-JS

I use React for developing, and normally, I use MUI and Emotion which is one of the CSS-in-JS libraries.

In here, I will introduce how to install and configure Stylelint to check the code style of CSS-in-JS.

Prepare project

To checkt CSS-in-JS by Stylelint, I will create a React project by CRA(create-react-app). If you want to know how to install CRA and how to create the React project by CRA, see the previous blog post.

Execute the command below to create a React project.

npx create-react-app stylelint-example --template typescript

And, execute the following command to install Emotion and MUI to the project.

npm install --save @mui/material @emotion/react @emotion/styled

And then, open the ./src/App.tsx file and modify it like the below to use CSS-in-JS for the styleling.

import styled from '@emotion/styled';

const Title = styled.h2`
  margin: 0 0 1rem 0;
  font-size: 1.5rem;
`;

function App() {
  return (
    <div>
      <Title>Learn React</Title>
    </div>
  );
}

export default App;

Install Stylelint for CSS-in-JS

To use Stylelint for checking CSS-in-JS, execute the command below to install Stylelint and required libraries.

npm install --save-dev stylelint stylelint-config-standard stylelint-config-prettier postcss postcss-syntax @stylelint/postcss-css-in-js

Configure Stylelint for CSS-in-JS

To use Stylelint, you need to create the .stylelintrc.json file and modify it like the below.

{
  "extends": ["stylelint-config-standard", "stylelint-config-prettier"],
  "overrides": [
    {
      "files": ["**/*.tsx"],
      "customSyntax": "@stylelint/postcss-css-in-js"
    }
  ],
  "rules": {
    "function-no-unknown": [true, { "ignoreFunctions": ["/\\${/"] }]
  }
}

Stylelint execution script for CSS-in-JS

To use Stylelint for checking CSS-in-JS, modify the package.json file like the below.

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

we set .gitignore to the --ignore-path option not to check unnecessary files.

Execute Stylelint for CSS-in-JS

Next, execute the following command to check Stylelint works well.

npm run lint:css

If you install and configure Stylelint well, you can see the following warning message.

src/App.css
  1:1   ✖  Expected class selector to be kebab-case  selector-class-pattern
  5:1   ✖  Expected class selector to be kebab-case  selector-class-pattern
 11:3   ✖  Expected class selector to be kebab-case  selector-class-pattern
 16:1   ✖  Expected class selector to be kebab-case  selector-class-pattern
 27:1   ✖  Expected class selector to be kebab-case  selector-class-pattern
 31:12  ✖  Expected keyframe name to be kebab-case   keyframes-name-pattern
 35:3   ✖  Expected empty line before rule           rule-empty-line-before

src/App.tsx
 4:3  ✖  Unexpected longhand value '0 0 1rem 0' instead of '0 0 1rem'  shorthand-property-no-redundant-values

src/index.css
 3:64  ✖  Unexpected quotes around "Roboto"     font-family-name-quotes
 3:74  ✖  Unexpected quotes around "Oxygen"     font-family-name-quotes
 4:6   ✖  Unexpected quotes around "Ubuntu"     font-family-name-quotes
 4:16  ✖  Unexpected quotes around "Cantarell"  font-family-name-quotes

The warning messages include the issues of the other files, but let’s focus the ./src/App.tsx file that we’ve modified. You can see the same warning message that we’ve seen in the CSS section. So, we know the Stylelint configured well and works well.

After modifying the src/App.tsx file like the below and executing Stylelint, you can see the issue fixed.

import styled from '@emotion/styled';

const Title = styled.h2`
  margin: 0 0 1rem;
  font-size: 1.5rem;
`;

function App() {
  return (
    <div>
      <Title>Learn React</Title>
    </div>
  );
}

export default App;

TypeError: Cannot read properties of undefined (reading ‘stringify’) error

Recently, I update the Stylelint version from 14.9.1 to 14.14.0 and get the error like the following.

TypeError: Cannot read properties of undefined (reading 'stringify')
    at Function.stringify (/node_modules/postcss-syntax/stringify.js:8:38)
    at MapGenerator.generate (/node_modules/stylelint/node_modules/postcss/lib/map-generator.js:328:12)
    at LazyResult.stringify (/node_modules/stylelint/node_modules/postcss/lib/lazy-result.js:277:20)
    at LazyResult.runAsync (/node_modules/stylelint/node_modules/postcss/lib/lazy-result.js:443:17)
    at LazyResult.async (/node_modules/stylelint/node_modules/postcss/lib/lazy-result.js:221:30)
    at LazyResult.then (/node_modules/stylelint/node_modules/postcss/lib/lazy-result.js:206:17)

To solve this error, you need to install postcss by executing the command following.

npm install --save-dev postcss

After installing postcss, when you execute the Stylelint command, you can see the error is resolved.

Complated

Done! we’ve seen how to install and configure Stylelint to check CSS/SCSS files. Also, we’ve seen how to use Stylelint to check CSS-in-JS files like styled-components/Emotion.

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