stylelint access practice pit summary


During team cooperation, when everyone's code has a custom formatting method, many conflicts often need to be solved when submitting the merge. At this time, we can use eslint+stylelint to restrict the team's code. The introduction of eslint configuration is relatively simple. There are many tutorials on the Internet, while most of the stylelint tutorials are vague. Here, I will introduce the pitfalls I encountered when introducing stylelint and the solutions.


stylelint is a powerful, modern code checking tool that helps you enforce style conventions in teamwork.

1. Install stylelint

yarn add -D stylelint

2. Configuration file

Using the stylelint detector requires a configuration object. You can create this object in three ways.

  • stylelint attribute in package.json.
  • . stylelintrc.js file
  • JS object output from stylelint.config.js file

Once any one of them is found, the search will not continue and the parsed object will be used. This time, the. stylelintrc.js file is used for configuration.

3. Use stylelint

To install the official documentation, you can run stylelint to detect the style code as follows.

--Fix is used for automatic repair, but it can't fix all problems.

// package.json
  "lint:css":"stylelint src/**/*.css --fix"

Step on pit point 1:

Because the style language used in my project is less. So it's definitely wrong to detect css, so we need to make some changes here

// package.json
  "lint:css":"stylelint src/**/*.less --fix"

So we can run this string of code

yarn lint:css postcss-less

As you can see, here are some reminders, which are simply translated as let's use the corresponding syntax to analyze our style. The corresponding syntax parser needs to be installed.

yarn add -D   postcss-less

The script is then modified again.

// package.json
  "lint:css":"stylelint src/**/*.less --fix  --custom-syntax postcss-less"

OK, here we can run the lint command normally to format our style code. Next, let's configure the lint rule

4. Configuration rules

stylelint is currently some workers who help translate Chinese documents. Students who are repellent to reading English documents can check them Chinese documents.

We first need to install three npm packages to help us improve the rules

yarn add -D stylelint-config-standard stylelint-order stylelint-config-css-modules

Stylelint config standard is the recommended configuration of stylelint. Stylelint order is used to sort the attributes of code when formatting css files. Stylelint config css modules is a css module scheme to handle style files

My profile looks like this:

// .stylelintrc.js
module.exports = {
    processors: [],
    plugins: ['stylelint-order'],
    extends: [
    rules: {
        "selector-class-pattern": [ // Naming conventions-
                "message": "Expected class selector to be kebab-case"
        "string-quotes":"single", // Single quotation mark
        "at-rule-empty-line-before": null,
        "at-rule-name-case": "lower",// Specifies the case of the @ rule name
        "length-zero-no-unit": true,  // Prohibit zero length units (can be repaired automatically)
        "shorthand-property-no-redundant-values": true, // Abbreviated attribute
        "number-leading-zero": "never", // Decimal without 0
        "declaration-block-no-duplicate-properties": true, // Fast repeat attribute declaration is prohibited
        "no-descending-specificity": true, // A lower priority selector that is overwritten by a higher priority selector is prohibited.
        "selector-max-id": 0, // Limit the number of ID selectors in a selector
        "max-nesting-depth": 3,
        "indentation": [2, {  // Specify indent warning reminder
            "severity": "warning"
        "order/properties-order": [ // Rule order
  • The processors attribute is not used this time, so it will not be introduced. Interested students can query the official documents.
  • plugins are community created rules or rule sets that support methodologies, toolsets, non-standard CSS features, or very specific use cases.
  • Extensions inherits an existing configuration file. (in my configuration, I inherited CSS module and the configuration officially recommended)
  • Rules rules determine what the detector wants to find and solve, so you can turn on the corresponding rules and carry out corresponding detection through this option. All rules must be explicitly configured because there is no default value.

In addition, defaultSeverity and ignoreFiles can also be configured here. Students who need them can file Found in.

Since I have annotated the corresponding rules in the configuration file to explain their functions, if any students have questions about this, please leave a message or add my friends to communicate~

Note: null disables the rule. You can override the officially recommended configuration rules in rules.

5. Ignore lint file

At this point, we can use stylelint to format the style code normally. However, there are often some code that does not need to be formatted in the project. For example, we will separate an overrides file to rewrite the style of antd. Obviously, there is no need to format here, because the selector naming of antd may be different from our specification. So we need to ignore this file when running lint.

    1. We can configure ignoreFiles in. stylelintrc.js.
    1. Create a. stylelintignore file.
    1. We can use the method of / * stylelint disable * / to ignore lint detection in code.

I use the second method, which is configured as follows:

// .stylelintignore

6. Automatic formatting

After the above configuration, in fact, we have achieved the purpose of specification, but if we have to run lint every time, it will undoubtedly increase our coding burden. Here are two ways to automatically format the code when we write style code.

6.1 stylelint vs code plug-in

We can search the stylelint plug-in in the vs code plug-in market. It looks like this

You can see that my plug-in is black because I don't use this plug-in. It has some bug s.

Briefly introduce the bug:

In ant D overrides, some codes have passed the lint rule we configured, but without this plug-in, it will report us a cssssyntax error. Moreover, after deleting some problem codes, the plug-in will report some logic code errors. This is unacceptable to me. So it was resolutely abandoned. You can choose according to the actual situation of your project~

6.2 webpack plugin

You can easily find webpack stylelint-plugin . This plug-in has been widely used ~ you can access it safely.

Why can a webpack plug-in help us format the style code? This is because the plug-in will help us detect the code when we recompile the hot update. fix according to the rules configured in the. stylelintrc.js file. If there are lint errors, you can choose to make the project unable to run, so as to avoid uploading styles without lint to the code base.

So I stepped on a lot of holes when using this plug-in. Next, I said one by one.

6.3 plug in pit collection

At the beginning. According to the writing method of various gods from Baidu, it only needs to be configured as follows:

new StyleLintPlugin({
    context: "src",
    configFile: path.resolve(__dirname, './stylelintrc.js'),
    files: '**/*.less',
    failOnError: false,
    quiet: true,
    syntax: 'less'

The ending is not unexpected and useless. The most terrible thing is that he will give you an illusion that there is no task problem when you run locally, which makes you mistakenly think that there is no problem with your code! In fact, this plug-in doesn't work.

In addition, if you use the vscode extension of stylelint in this configuration, there will be a lot of red waves that explode your mentality ~ ~ ~.

After my stepping on the pit, I finally completed a configuration without error reporting, illusion, error checking and ignoring my configuration!

    new StylelintPlugin({
      configFile: path.resolve(__dirname, './.stylelintrc.js'),
      extensions: ['less'],
      files: 'src/**/*.less',
      fix: true,
      customSyntax: 'postcss-less',
      lintDirtyModulesOnly: true,
      threads: true,
      exclude: ['node_modules', 'src/styles/antd-overrides.less'],

Here I want to explain the usage of each field in detail.

  • configFile has nothing to say. Load the configuration file.
  • extensions specifies the extension to check. You must configure it here, or you will detect your tsx.
  • files specifies the detection directory.
  • fix this is the point. This is the key configuration of automatic formatting.
  • customSyntax, this is the key again!!!! Be sure to add this configuration. syntax is used in the boss configuration of Baidu. This configuration is outdated. You need to use customSyntax, and value must be the postcss less package you installed before. This configuration is not even in the official webpack documentation. I'm ready to mention the issue
  • lintDirtyModulesOnly only checks for changed files and skips the check at startup.
  • threads automatically determines the pool size based on the number of CPUs.
  • exclude is very important. In practice, I found that the webpack plugin did not read the ignore rules I configured in. stylelintignore, resulting in a lot of errors when the project was running. Must match!!!!

7. commit detection

This is relatively simple. If the project has previously configured the commit detection during eslint, you only need to add the detection style to the script. The configuration is as follows

  "lint-staged": {
    "*.{ts,tsx}": [
      "eslint --ext js,ts,tsx --fix",
      "git add"
    "*.less": [
      "stylelint --fix  --custom-syntax postcss-less",
      "git add"

In fact, we don't need to run yarn lint:css here, because if so, we will fully detect all styles under src during commit. However, in fact, we only need to detect the modified files. Special note: be sure to add -- custom syntax postcss less.

Well, here we are.... It's not over yet.

Let's sort out the workflow of stylelint

  • . stylelintrc configuration rule.
  • package.json configuration script command
  • . stylelintignore configure ignore rules
  • Stylelint webpack plugin configure automatic formatting rules
  • Lint staged configuration commit rules

First, when running the project, you will read the. stylelintrc file, check the code through the webpack plugin according to the rules inside, and format it automatically. When lint:css is run, the. stylelintignore will be read, and the related files will be ignored during detection. When we commit after modifying the code, lint staged will help us do a pre submission detection to avoid uploading unformatted code.

7.1 pits found during combing process

After I finished configuring stylelint, I started the passion coding phase. However, when I set a transparent color rgba for the element according to the design drawing. The intimate plug-in will help me format rgba into rbg color. like this:

After automatic formatting, the beep becomes like this

RGB (0 / 12%) what is this? At first I didn't care, until I found that this style became like this on the page

Don't you tease me? You format it. How did it become this thing???

So I hurried to Baidu. Baidu couldn't find the answer... Then Google finally found an answer that looked like an answer

Explain it briefly. This is a relatively new css specification. sass specification is not yet supported. Analogy to my less. That is, my less specification doesn't support it yet. Because the less version used in the project is 3 +. It's not the latest. So it's normal not to support it. My less recognizes the transparent rgb of my new specification as the third parameter, followed by / division. 0 divided by 12%, tell me loudly what it is? Or 0

So my less is not wrong, the wrong is the world!

With the attitude of trying, I went to the browser and directly wrote an RGB (0 / 12%) to see if the support is not supported. The results are as follows:

Yes, browser support! That's easy. There are two solutions before us

  1. Let less support this color scheme
  2. Let stylelint not format

With the method, I went to the changelog of the official warehouse of less. I tried to mention even half the word rgb in the latest update, but I didn't. Or maybe my eyes are not very good ~ ~. In short, the first method failed.

In the second way, we should first know which rule of stylelint formats rgba into rgb. I made a lot of attempts. And did a lot of Baidu. Not what I expected. Baidu can't find it. It's not right to try. The road is narrow.

So I changed my mind. I went to see the officially recommended stylelint config standard configuration library. As shown in the figure: pay attention to the red box

In version 23, the color was already a percentage. This is also the latest version and the version in my project. So what's certain is that this library must have formatted it for me!!!

So how can we make him not format? Check other versions of this library. If rgba appears in any version, this version will not be automatically formatted.

Everything comes to him who waits. I only looked for one version and found it

Therefore, the library version in the project will be downgraded ~, so that rgba will not be formatted into rgb! be accomplished.


It's not terrible to encounter problems. The terrible thing is that Baidu can't find the answer.

If Baidu is less than, you can Google. Remember, remember.

Keywords: Javascript Front-end less React css

Added by Altec on Sat, 06 Nov 2021 05:40:00 +0200