foreword
When working as a team, when everyone's code has a custom format, many conflicts are often resolved when submitting a merge. At this time, we can use eslint
+ stylelint
to constrain the team's code. The configuration introduction of eslint
is relatively simple. There are many tutorials on the Internet, and most of the tutorials of stylelint are vague. Here, I will introduce the pits I encountered in the introduction stylelint
and the solutions.
text
stylelint
is a powerful, modern code inspection tool that can help you enforce 样式约定
in teamwork.
1. Install stylelint
yarn add -D stylelint
2. Configuration file
Using the stylelint detector requires an 配置对象
and you can create this object in three ways.
- The stylelint attribute in
package.json
. -
.stylelintrc.js
file -
stylelint.config.js
js object output by file
Once any of them are found, no further lookup will be done, parsing will take place and the parsed object will be used. This time, the .stylelintrc.js
file is used for configuration.
3. Using stylelint
To install the official documentation you can run stylelint to detect style code as follows.
--fix
used for automatic repair, but not all problems.
// package.json
"scripts":{
"lint:css":"stylelint src/**/*.css --fix"
}
Stepping point 1:
Since the style language used in my project is less. So it is definitely wrong to detect css, so here we need to make a little change
// package.json
"scripts":{
"lint:css":"stylelint src/**/*.less --fix"
}
So we can run this code
yarn lint:css postcss-less
As you can see, some reminders are reported here, which are simply translated to let us use the corresponding grammar to parse our style. And the corresponding parser needs to be installed.
yarn add -D postcss-less
So modify the script again.
// package.json
"scripts":{
"lint:css":"stylelint src/**/*.less --fix --custom-syntax postcss-less"
}
OK At this point, we can run the lint command normally to format our style code. Next we configure the lint rules
4. Configure the rules
At present, some workers in stylelint have helped to translate Chinese documents. Students who are reluctant to read English documents can view 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
stylelint-config-standard
is the recommended configuration for stylelint, stylelint-order
is used to sort the properties of the code when formatting css files. stylelint-config-css-modules
is the scheme of css-module
to process 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": [ // 命名规范 -
"^([a-z][a-z0-9]*)(-[a-z0-9]+)*$",
{
"message": "Expected class selector to be kebab-case"
}
],
"string-quotes":"single", // 单引号
"at-rule-empty-line-before": null,
"at-rule-no-unknown":null,
"at-rule-name-case": "lower",// 指定@规则名的大小写
"length-zero-no-unit": true, // 禁止零长度的单位(可自动修复)
"shorthand-property-no-redundant-values": true, // 简写属性
"number-leading-zero": "never", // 小数不带0
"declaration-block-no-duplicate-properties": true, // 禁止声明快重复属性
"no-descending-specificity": true, // 禁止在具有较高优先级的选择器后出现被其覆盖的较低优先级的选择器。
"selector-max-id": 0, // 限制一个选择器中 ID 选择器的数量
"max-nesting-depth": 3,
"indentation": [2, { // 指定缩进 warning 提醒
"severity": "warning"
}],
"order/properties-order": [ // 规则顺序
"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',
],
}
};
-
processors
The attribute is not used this time, so it will not be introduced. Interested students can check the official document. -
plugins
are rules or rule sets created by the community to support methodologies, toolsets, non -standard CSS features, or very specific use cases. -
extends
Inherit an existing configuration file. (In my configuration, css-module and the official recommended configuration are inherited) -
rules
rule decides what the detector is looking for and what to solve, so with this option you can enable the corresponding rule and perform the corresponding detection. All rules must be configured explicitly because there is no default value .
In addition, there are defaultSeverity
and ignoreFiles
which can also be configured here. Students who need it can find it in the document .
Since I have commented on the corresponding rules in the configuration file and explained its function, if any students have questions about this, please leave a message or add me as a friend to communicate~
注意:
null is a disabled rule. You can override the officially recommended configuration rules in rules .
5. Ignore lint files
At this point, we can use stylelint to format the style code normally. However, there are often some code that does not need formatting in the project. For example, we will extract an overrides file separately to rewrite the style of antd. Obviously there is no need for formatting here, because antd's selector naming may not be the same as our specification. So we need to ignore this file when running lint.
- We can configure ---1baa1969ce9c21afb8370a8b20046aa9
.stylelintrc.js
inignoreFiles
. - Create the
.stylelintignore
file. - We can use the method of
/* stylelint-disable */
to ignore lint detection on the code.
I used the second method, the configuration is as follows:
// .stylelintignore
*.js
*.tsx
*.ts
*.json
*.png
*.eot
*.ttf
*.woff
*.css
src/styles/antd-overrides.less
6. Auto format
After completing the above configuration, we have actually achieved the purpose of the 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 plugin
We can search for the plugin in the vs-code plugin market stylelint
plugin, it looks like this
You can see that I am black here, this is because I don't use this plugin, it has some bugs.
Briefly describe where the bug is:
There is some code in antd-overrides that has passed the lint rules we configured, but without this plugin, it will give us a report CssSyntaxError
. And after deleting some problematic code, this plugin will report some logic code errors. This is not acceptable to me. So decided to abandon it. You can choose according to the actual situation of your project~
6.2 webpack plugin
You can easily find stylelint-plugin for webpack. It means that this plugin has been widely used ~ you can access it with confidence.
Why a webpack plugin can help us format the style code is because when we recompile in a hot update, this plugin will help us detect the code. And fix it according to the rules configured in the .stylelintrc.js
file. You can choose to make the project inoperable if there are lint errors, and avoid uploading styles without lint to the codebase.
So I stepped on a lot of pits when using this plugin, and then I will talk about them one by one.
6.3 Highlights of plug-ins stepping on pits
At the very beginning. According to the writing method of the various gods from Baidu, you only need to configure it like this:
new StyleLintPlugin({
context: "src",
configFile: path.resolve(__dirname, './stylelintrc.js'),
files: '**/*.less',
failOnError: false,
quiet: true,
syntax: 'less'
})
The ending was unexpected and useless. The most terrifying thing is that he will give you a kind of 假象
, there is no task problem when you run it locally, making you mistakenly think that your code has no problems! Actually, this plugin didn't work.
In addition, if you use the vscode extension of stylelint in this configuration, there will be a lot of things that will make your mind explode 红波浪~~~~
.
After my stepping on the pit, I finally completed a configuration with no errors, no illusions, no error checking, and no ignoring my ignoring 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 would like to explain the usage of each field in detail.
-
configFile
Nothing to say, load the config file. -
extensions
Specifies the extension to check. It must be configured here, otherwise it will detect your tsx. -
files
Specify the detection directory. -
fix
This is the point. This is where the key configuration for automatic formatting comes in. -
customSyntax
This is the key again! ! ! ! Be sure to add this configuration. Baidu's big brother configuration usessyntax
. This configuration is outdated, you need to usecustomSyntax
and the value must be thepostcss-less
package that you installed before. This configuration is not even in the official webpack documentation.我已经准备去提issue了
-
lintDirtyModulesOnly
Only check files with changes, skip checking at startup. -
threads
will automatically determine the size of the pool according to the number of CPUs. -
exclude
This is very important. Because I found in practice that webpack-plugin did not read the ignore rules I configured in.stylelintignore
, which resulted 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 of 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, there is no need to run yarn lint:css
, because if this is the case, all the styles under src
will be fully detected when committing, but in fact, we only need to detect the modified files. Special Note: Be sure to add --custom-syntax postcss-less
.
Alright, here we go. . . . It's not over yet.
Let's sort out the workflow of stylelint
-
.stylelintrc
Configuration rules. -
package.json
Configuration script command -
.stylelintignore
Configure ignore rules -
stylelint-webpack-plugin
Configure automatic formatting rules -
lint-staged
Configure commit rules
First, when running the project, it will read the .stylelintrc
file, and check the code through webpack-plugin according to the rules inside, and format it automatically. When running lint:css
, it will read .stylelintignore
and ignore related files when detecting. When committing after modifying the code, lint-staged will help us to detect before making a commit, so as to avoid uploading unformatted code.
7.1 Pit found when sorting out the process
After I finished the configuration of stylelint, I started the passionate coding session. However, I set a color with transparency to the element according to the design drawing rgba
. The thoughtful plugin will help me to format ---8a53bb159ae5ba8c4fde5ae051c4f445 rgba
into rbg
color. like this:
After automatic formatting, the beep becomes like this
rgb(0 0 0 / 12%)
what is this? At first I didn't care, until I found that on the page the style became like this
Isn't this kidding me, you format it and format it, how did it become this thing? ? ?
So I hurried to Baidu, but Baidu couldn't find the answer. . . Then googled again and finally found an answer that looked like the answer
Briefly explain. This is a relatively new CSS specification. The sass specification is not yet supported. Analogy to my less. That is, my less specification does not support it yet. Because the version of less used in the project is 3+. Not up to date yet. So it's just normal to not support it. My less recognizes my new norm with transparency rgb
as the third parameter /
is division. 0除以12%
Tell me out loud how much? still 0
So my less is not wrong with this world!
With the mentality of trying it, I went to the browser and wrote it directly rgb(0 0 0 / 12%)
to see if it is supported. The result is as follows:
That's right, browser support! That's easy, there are two solutions in front of us
- Let less support this color scheme
- Let stylelint not format
With the method, I went to find the official warehouse of less
changelog
I tried to even mention half of the words in the latest version of the update rgb
, but not at all. It may also be that my eyesight is not very good~~. Anyway, the first method fails.
Then we use the second method. First, we need to know which rule of rgba
into rgb
. I have tried a lot. And do a lot of Baidu. Not as I expected. Baidu is not available. Trying is wrong. The road is narrow.
So I changed my mind and went to see the official recommended stylelint-config-standard
configuration library. Pictured: everyone pay attention to the red box
At version 23, colors were already percentages. This is also the latest version and the version in my project. So what is certain is that this library must have formatted it for me! ! !
So how do we make it unformatted? Go to check other versions of this library, but if rgba appears in which version, then this version will not be automatically formatted.
Hard work pays off. I only looked for one version and found it
So downgrade the library version in the project~, so that rgba
will not be formatted into rgb
! You're done.
postscript
It is not terrible to encounter problems, but the terrible thing is that Baidu does not have the answer.
If Baidu is not available, you can also Google. Remember remember.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。