preface
When working in a team, you can use ESLint +stylelint to constrain the team’s code when submitting the merge, as there are many conflicts that need to be resolved when each person’s code has a custom format. Configuration introduction for ESLint is relatively simple, and there are many tutorials online, while those for Stylelint are mostly vague. Here, I describe the potholes I encountered in introducing Stylelint, and how to fix them.
The body of the
Stylelint is a powerful, modern code checking tool that helps you enforce style conventions in team work.
1. Install stylelint
yarn add -D stylelint
Copy the code
2. Configuration file
Using the Stylelint detector requires a configuration object, which you can create in one of three ways.
package.json
The stylelint property in..stylelintrc.js
filestylelint.config.js
File output js object
Once any of them are found, the search is stopped and the parsed object is used. The.stylelintrc.js file is used for configuration.
3. Use stylelint
You can run the stylelint to detect style code in the following ways.
–fix Is used to automatically fix, but cannot fix all problems.
// package.json
"scripts":{
"lint:css":"stylelint src/**/*.css --fix"
}
Copy the code
Step pit point 1:
Since the style language used in my project is less. So detecting CSS is definitely wrong, so we need to make a change here
// package.json
"scripts":{
"lint:css":"stylelint src/**/*.less --fix"
}
Copy the code
So we can run this code
yarn lint:css postcss-less
Copy the code
As you can see, there are some reminders, which simply translate to let’s use the corresponding syntax to parse our style. The corresponding syntax parser needs to be installed.
yarn add -D postcss-less
Copy the code
The script is changed again.
// package.json
"scripts":{
"lint:css":"stylelint src/**/*.less --fix --custom-syntax postcss-less"
}
Copy the code
OK at this point we can normally run the lint command to format our style code. Next we configure the Lint rule
4. Configure rules
Stylelint is currently translated from Chinese documents by some workers. Students who have a certain aversion to reading English documents can check the Chinese documents.
We first need to install three NPM packages to help us refine the rules
yarn add -D stylelint-config-standard stylelint-order stylelint-config-css-modules
Copy the code
Stylelint-config-standard is the recommended configuration for Stylelint, which is used to sort the properties of the code when formatting CSS files. Stylelint-config-css-modules is a CSS-module scheme for handling style files
My configuration file looks like this:
// .stylelintrc.js module.exports = { processors: [], plugins: ['stylelint-order'], extends: [ "stylelint-config-standard", "stylelint-config-css-modules" ], rules: { "selector-class-pattern": [/ / naming conventions - "^ ([a-z] [a - z0-9] *) (- / a - z0-9 +) * $", {" message" : "Expected class selector to be kebab-case"}], "string-quotes":"single", // single quotes" at-rule-empty-line-before": Null, "at-rule-no-unknown":null, "at-rule-name-case": "lower",// Specify the case of @ rule name "length-zero-no-unit": True, // Disable zero-length units (auto-fixable) "total-property-no-redundant -values": true, // Shorthand property "number-leading-zero": "Never ", // with 0 "declaration-block-no-duplicate-properties": true, // Disallow" no-rapid-properties ": True, // Disallows a lower-priority selector to be overridden after a higher-priority selector. "Selector-max-id ": 0, // Limit the number of ID selectors in a selector "max-nesting-depth": 3, "indentation": [2, {// Specify the indentation warning to remind "severity": "warning" }], "order/properties-order": [/ order/rules "position", "top", "right", "bottom", "left", "z - index", "display", "float", "width", "height", 'Max - width, 'max-height', 'min-width', 'min-height', 'padding', 'padding-top', 'padding-right', 'padding-bottom', 'padding-left', 'margin', 'margin-top', 'margin-right', 'margin-bottom', 'margin-left', 'margin-collapse', 'margin-top-collapse', 'margin-right-collapse', 'margin-bottom-collapse', 'margin-left-collapse', 'overflow', 'overflow-x', 'overflow-y', 'clip', 'clear', 'font', 'font-family', 'font-size', 'font-smoothing', 'osx-font-smoothing', 'font-style', 'font-weight', "line-height", 'letter-spacing', 'word-spacing', "color", "text-align", 'text-decoration', 'text-indent', 'text-overflow', 'text-rendering', 'text-size-adjust', 'text-shadow', 'text-transform', 'word-break', 'word-wrap', 'white-space', 'vertical-align', 'list-style', 'list-style-type', 'list-style-position', 'list-style-image', 'pointer-events', 'cursor', "background", "background-color", "border", "border-radius", 'content', 'outline', 'outline-offset', 'opacity', 'filter', 'visibility', 'size', 'transform', ], } };Copy the code
processors
Attribute is not used this time, so no introduction, interested students can check the official document.plugins
Are rules or rule sets created by the community that support methodologies, tool sets,non-standardCSS features or very specific use cases.extends
Inherits an existing configuration file. (In my configuration, I inherited csS-Module and the official recommended configuration)rules
Rules determine what the detector looks for and resolves, so with this option you can turn on the rules and perform the checks accordingly. All rules must be explicitly configured becauseNo default value.
In addition, defaultSeverity and ignoreFiles can also be configured here. Students who need them can find them in the document.
Since I have annotated the corresponding rule in the configuration file to explain its function, if you have any questions about this, please leave a comment or add my friend to communicate ~
Note: NULL disables the rule. You can override official recommended configuration rules in Rules.
5. Ignore lint files
The stylelint can now be used to format the style code normally. However, there are often some code in the project that does not need formatting. For example, we will separate out a overrides file to rewrite antD style. Obviously no formatting is required, because antD’s selector names may differ from our specification. So we need to ignore this file when running Lint.
-
- We can do it at
.stylelintrc.js
In the configurationignoreFiles
.
- We can do it at
-
- create
.stylelintignore
File.
- create
-
- We can get through
/* stylelint-disable */
Method to quickly ignore Lint for code.
- We can get through
I used the second method with the following configuration:
// .stylelintignore
*.js
*.tsx
*.ts
*.json
*.png
*.eot
*.ttf
*.woff
*.css
src/styles/antd-overrides.less
Copy the code
6. Automatic formatting
After the configuration above, we’ve already achieved the goal of the specification, but having to run Lint every time would definitely add to our coding burden. Here are two ways to automatically format code as we write style code.
6.1 Stylelint VS-Code plug-in
We can search the Stylelint plugin in the VS-Code plugin market and it looks something like this
You can see I’m in black here because I don’t use this plugin, it has some bugs.
A brief description of the bug:
There is some code in antD-Overrides that passes our configured Lint rule, but no plugin will give us a CssSyntaxError. The plugin also reports logical code errors after removing some problematic code. This is not acceptable to me. So he abandoned it decisively. You can choose according to the actual situation of your project
6.2 webpack plugin
You can easily find webpack’s stylelint-Plugin. This means that the plugin is already widely used ~ you can safely access.
The reason why a Webpack plug-in can help us format the style code is because it checks the code while we recompile with hot updates. The stylelintrc.js file is fixed according to the rules configured in the. Stylelintrc.js file. You can choose to disable the project if there are lint errors to avoid uploading non-Lint styles to the code base.
So I stepped in a lot of holes when using this plug-in, and I will say one by one.
6.3 Plug-in trampling pit collection
At the very beginning. According to baidu to the various gods written, only need to configure this can be:
new StyleLintPlugin({
context: "src",
configFile: path.resolve(__dirname, './stylelintrc.js'),
files: '**/*.less',
failOnError: false,
quiet: true,
syntax: 'less'
})
Copy the code
The ending was predictable and useless. The scariest part is that it will give you the illusion that there are no task problems when you are running locally, making you think there are no problems with your code! In fact, the plugin does not work.
Plus, there’s a whole bunch of mind-blowing red waves ~~~~ if you use stylelint’s vscode extension.
After my step pit, finally completed a no error, no false appearance, no error check, no ignore my ignore configuration 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'],
})
Copy the code
Here I want to explain the use of each field in detail.
configFile
Nothing to say. Load the configuration file.extensions
Specifies the extension to check. It must be configured here, otherwise it will check your TSX.files
Specify the detection directory.- Fix this is the main point. This is where the key configuration for automatic formatting comes in.
customSyntax
Again, this is key !!!! Be sure to add this configuration, Baidu to the big guy configuration is usedsyntax
. This configuration is outdated and needs to be usedcustomSyntax
And the value must be one that you have installed beforepostcss-less
The package. This configuration is not even in the official WebPack documentation.I'm ready to make an issue
lintDirtyModulesOnly
Check only the files that have changed. Skip the check on startup.threads
The pool size is automatically determined based on the number of cpus.exclude
This is very important. Because I found in practice that the Webpack-plugin didn’t read my code in.stylelintignore
Ignore rules configured in the., resulting in a lot of errors when the project runs. Be sure to go with !!!!
7. Commit detection
This is easier, if the project has previously configured commit detection for ESLint, you just need to add the detection style to the script. 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"
]
}
Copy the code
There is no need to run YARN Lint: CSS, because if you do this, all SRC styles will be checked at commit, whereas we only need to check the changed files. Special note: be sure to add –custom-syntax postcss-less.
All right, here we go… It’s not over yet.
Let’s walk through stylelint’s workflow
.stylelintrc
Configure rules.package.json
Configuration Script Commands.stylelintignore
Configuring the Ignore Rulestylelint-webpack-plugin
Configure automatic formatting ruleslint-staged
Configuring a COMMIT Rule
The. Stylelintrc file is read when the project is first run, and the code is checked by webpack-plugin according to the rules in it, and automatically formatted. Lint: CSS is read when run. Related files are ignored for stylelintignore detection. Lint-staged code will be tested before committing after modification to avoid uploading unformatted code.
7.1 Pits found during carding process
After I finished the configuration of stylelint, I started the passion coding process. However, WHEN I set the element to a color rGBA with transparency based on the design. The thoughtful plugin will help me format RGBA to RBG color. Like this:
After automatic formatting, the du looks like this
RGB (0.00/12%) what the hell is this? I didn’t care until I noticed that on the page it looked like this
This is not kidding me, you format format, how to become this thing??
So hurriedly go to Baidu, Baidu is not the answer… Then I googled and finally found an answer that looked like an answer
Just a quick explanation. This is a relatively new CSS specification. The SASS specification does not yet support it. Analogy to my less. My LESS specification doesn’t support it yet. The less version used in the project is 3+. It’s not up to date. So it’s perfectly normal not to support it. My LESS identifies my new specification’s RGB with transparency as the/after the third argument is division. What is zero divided by 12% out loud? Is zero!
So my less is not wrong wrong is this world!
I went to the browser to directly write an RGB (0.00/12%) to see if it is supported. The results are as follows:
That’s right, browser support! Well, that’s easy. We have two solutions in front of us
- Let less support this color scheme
- Leave the stylelint unformatted
With the method, I searched the changelog of the official warehouse of LESS. I tried to mention even half of THE WORD RGB in the update of the latest version, but there was no such word. Or maybe my eyes aren’t very good. Anyway, the first method fails.
So we use the second method, first to know which rule in the stylelint formats RGBA to RGB. I tried a lot. And do a lot of Baidu. That’s what I expected. Baidu is not available. It’s not right to try. The road narrowed.
Instead, I check out the officially recommended Stylelint-Config-Standard library. Picture: Notice the red box
As of version 23, the colors are already percentages. This is also the latest version, which is the version in my project. Sure enough, it must be the library that formatted it for me!
So how do we get it unformatted? If you look at other versions of the library, any version that has RGBA in it will not be automatically formatted.
Everything comes to him who waits. I only looked for one version, and I found it
So the library version of the project do downgrade processing ~, so that rGBA will not be formatted into RGB! And you’re done.
Afterword.
Encountered problems are not terrible, terrible is baidu is not the answer.
If Baidu can not also Google. Remember to remember.