Automatically Format CSS with StyleHint

Posted in tools, blogs on November 4, 2020 by Henk Verlinde ‐ 2 min read

Automatically Format CSS with StyleHint

Introduction

When developing with CSS, it is necessary to decide some rules. Use stylelint and manage your code. Code rules use stylelint-config-standard .

  1. Package management tool npm
  2. Use module stylelint prettier
  3. Usage rules stylelint-config-standard

install node

Install node and make npm available.

create package.json

In your working folder, type the following command. The defaults for all interactively asked items are fine.

npm init

You will have a package.json.

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

Install stylelint, rules and formatters Install the required modules by running the following in your working directory.

npm install stylelint stylelint-config-standard prettier

Write stylelint rules

In the working directory, create a [.stylelintrc] file and write the following

{
  "extends": "stylelint-config-standard",
  "rules": {
    "string-quotes": "double"
  }
}

Edit package.json

Add the following to scripts.

"format": "prettier --write"
{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "format": "prettier --write"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "prettier": "^1.18.2",
    "stylelint": "^10.1.0",
    "stylelint-config-standard": "^18.3.0"
  }
}

The file name for describing the test code is [test.css]. According to the rules of stylelint-config-standard, indentation other than 2 is not allowed as an additional rule.

.add {
    content: 'x';
}

format

Execute the following command and check if it is modified according to the rules.

npm run format test.css
.add {
  content: "x";
}

end

Once the file indentation is corrected, you are done. thank you for your hard work.