Do you need a semicolon at the end of each statement? Use two Spaces or four Spaces?
There are countless discussions about code formats, and there is no absolute right or wrong, everyone has their own code preferences. That’s fine if it’s solo development, but when it comes to co-development it inevitably leads to code style conflicts:
Colleague A likes to use two Spaces and commit the code, while Colleague B likes to use four Spaces and has kindly changed the double Spaces back, which inevitably leads to useless Git commit records (and bad relationships with colleagues)
So that’s code format. There’s another important aspect of code specification besides code format: code quality. Using undefined variables? Use reserved words to define variables? Does a function return value need to be typed? Is the use of any completely disabled? The internal logic involved in the code is code quality.
A problem with code quality means a potentially buggy application, and a problem with code format is bad looking at best.
So coding specifications need to be specified and enforced by everyone on the team, with tools to review the code and provide formatting capabilities.
Using ESLint + Prettier your team’s coding specification. By the end of this article you should know:
- What is ESLint, Prettier? What problems do they solve?
- Configuration and use of ESLint
- ESLint configuration package
- ESLint and Prettier, how do you use them together
- Know Git hooks and can check submitted code using the specified hooks
ESLint is used on a basic basis
ESLint is an open source JavaScript code-checking utility that uses ESPREe to parse code into abstract syntactic scripts (AST), perform static code analysis using the AST, and give tips on both format and quality:
- Tab length, maximum number of lines in a function, trailing semicolons, etc
- Code-quality rules: unused variables, use of reserved words, contamination of global variables, etc.
In addition, ESLint is fully plug-in, and each rule is a plug-in. ESLint already has some default rules built in to make it easier to use, and developers can customize rules and add more rules at run time.
Install and use
After NPM inite -y initializes a project, execute:
npm install -D eslint
npx eslint --init
Copy the code
To create a default.eslintrc configuration file, create a new index.js file:
const data = 'semi';
Copy the code
Then performnpx eslint index.js
You’ll see the result of ESLint:
configuration
ESLint provides two main configurations:
- Use JavaScript comments in the source file of your code
- Use a separate
.eslintrc.*
Configuration file, or directly inpackage.json
The use ofeslintConfig
Field specifies the configuration. ESLint automatically finds and reads them.
If there are multiple configuration files in the same directory, only one configuration file will be used. The priority is as follows:
.eslintrc.js
.eslintrc.yaml
.eslintrc.yml
.eslintrc.json
.eslintrc
package.json
The main parameters are as follows:
env
: Specifies the environment in which the script is run. Each environment defines a predefined set of global variables.globals
: Additional global variables accessed by the script during execution.rules
: Modifies the rule.extends
: Inherits rules enabled in other configuration files.plugins
: Use third-party plug-ins.parser
: parser.parserOptions
: Parser configuration.
rules
Rules is a specific code-checking option. To change a rule setting, you must set the rule ID to one of the following values:
"off"
或0
– Close rule"warn"
或1
– Enable rules with warning level errors:warn
(Does not cause the program to exit)"error"
或2
– Enable rules, use error level errors:error
(When triggered, the program exits)
{
"rules": {
"eqeqeq": "off".If a rule has additional options, they can be specified using array literals
"quotes": ["error"."double"].// When configuring a rule defined in a plugin, you must use the plugin name/rule ID
"plugin1/rule1": "error"}}Copy the code
All rules are disabled by default. In a configuration file, you can start rules recommended by ESLint by turning on “extends”: “ESLint :recommended”. For more rules, see: Rules
plugins
ESLint supports the use of third-party plugins. Before you can use the plug-in, you must install it.
When configuring plug-ins in a configuration file, you can use the plugins keyword to store a list of plug-in names. The plugin name can omit the eslint-plugin-prefix, using eslint-plugin-react as an example:
{
"plugins": ["react"]}Copy the code
extends
Extends provides the option to inherit from other configuration files. Properties can be a third-party package, a path to a configuration file, or an array of strings (each configuration inherits the configuration that precedes it).
The extends property value can omit the package name prefix eslint-config-, such as eslint-config-standard:
{
"extends": "standard"
}
Copy the code
Some plug-ins can also output one or more named configurations, where the extends consists of the following properties:
plugin:
- Package name (omits prefix
eslint-plugin-
, such as,react
) /
- Configure the name (e.g
recommended
)
Using eslint-plugin-react as an example, this plugin provides recommended, all, etc. : an export configuration for eslint-plugin-react is implemented as follows:
{
"extends": [
"plugin:react/recommended"],}Copy the code
The parser and parserOptions
Parser refers to a parser that processes.js,.ts files for AST use. ESLint uses espree as the parser by default.
In addition to Espree, there are the following Parser models that are compatible with ESLint:
- esprima
- @babel/eslint-parser – a wrapper around the Babel parser to make it compatible with ESLint.
- @typescript-esLint /parser – Converts typescript to estREE compatible form for use in ESLint.
Options for the Parser can be configured by parserOptions, which is passed in as parserOptions. By default, ESLint supports ECMAScript 5 syntax.
An example configuration is as follows:
{
"parserOptions": {
// The version of ECMAScript used
"ecmaVersion": 6.// Set to "script" (default) or "module" (if your code is an ECMAScript module).
"sourceType": "module",}}Copy the code
env
Specifies the environment in which the script runs. Each environment defines a predefined set of global variables, and multiple environments can be defined.
For example, if browser is configured, you can use the browser global variable window:
{
"env": {
"browser": true,}};Copy the code
Common environments are as follows:
- Browser – a global variable in the browser environment.
- Node.js global variable and node.js scope.
- Commonjs – CommonJS global variables and CommonJS scopes (for Browserify/WebPack packaged browser-only code).
- Shared-node-browser-node. js and browser are common global variables.
- Es6 – Enables all ECMAScript 6 features except modules (this automatically sets the ecmaVersion parser option to 6).
globals
The no-undef rule warns when accessing variables that are not defined in the current source file. If you want to use additional global variables in your source file, you need to define these variables in ESLint:
{
"globals": {
// The var1 variable can be overridden
"var1": "writable".// var2 is read-only and cannot be overwritten
"var2": "readonly"}}Copy the code
VSCode prompt
NPX ESLint is too cumbersome to use the command line every time. Can the IDE check the code at development time and show errors? Open VSCode Extensions, search for ESlint, and install the extension. You will find that the source files are developed in VSCode, and errors will be reported directly in the IDE.
NPX esLint –fix can also fix some rules, and.vscode/settings.json can format code in the IDE:
{
"eslint.validate": [
"javascript"."javascriptreact"."typescript"."typescriptreact",]."editor.codeActionsOnSave": {
"source.fixAll.eslint": true,}}Copy the code
ESLint configuration package
OK~ Now that you’ve mastered the basics of using ESLint, your team has discussed and specified a set of coding specifications. At this point, the.eslintrc configuration file is already hundreds of lines long, making it cumbersome for every developer to configure so many rules locally and difficult to synchronize with subsequent updates to the specification. So you create an NPM package, eslint-config-mine, as the team’s ESLint configuration package:
module.exports = {
"extends": "eslint:recommended"."rules": {
// enable additional rules
"indent": ["error".4]."linebreak-style": ["error"."unix"]."quotes": ["error"."double"]."semi": ["error"."always"].// override default options for rules from base configurations
"comma-dangle": ["error"."always"]."no-cond-assign": ["error"."always"].// disable rules from base configurations
"no-console": "off",}}Copy the code
Developers on the team simply need to install the eslint-config-mine dependency and introduce it in.eslintrc:
{
"extends": "mine"
}
Copy the code
Isn’t it too much of a hassle to have so many rules, each of which needs to be discussed? Is there a configuration package available to use? You’ll find that many large companies have published their own standards, but Airbnb does the best, and can be used directly by installing eslint-config-Airbnb:
{
"extends": "airbnb"
}
Copy the code
Prettier
Doesn’t Prettier need to be used when ESLint tackles both format and quality? But ESLint mainly deals with code quality, not formatting. Prettier takes over the format of code in two types of problems and fixes it automatically.
NPM install -d prettier prettier dependency NPM install -d prettier dependency
const data = 'semi'
console.log(data)
Copy the code
NPX prettier index.js –write the file is formatted as:
const data = "semi";
console.log(data);
Copy the code
Of course, if you want to use single quotes, create a.prettierrc.js and configure it as follows:
module.exports = {
singleQuote: true
};
Copy the code
You’ll notice that the formatted code uses single quotes.
ESlint + Prettier used together
ESLint, Prettier, formatting ESLint, Prettier, formatting ESLint checks include code format and code quality, but Prettier only does formatting for code quality. For code validation, code format is a one-click fix, and code quality generally needs to be fixed manually (function return values are not specified, if any).
While ESLint and Prettier can both fix code formats, there must be some conflicts, so Prettier only inspects code format and fixes while ESLint only inspects code quality.
configuration
Eslint-config-prettier is a configuration package for ESLint that shuts down the code formatting rules prettier already handles, first installing dependencies:
npm i -D prettier eslint-config-prettier
Copy the code
Then import this configuration package in eslintrc:
{
"extends": [
"prettier"."some-other-config-you-use"]}Copy the code
ESLint then turns off max-len, quotes, curly, and other rules, leaving formatting fixes to Prettier and code checks to ESLint:
NPX prettier SRC --write eslint NPX eslint SRCCopy the code
Code review based on HusKY, Lint-staged code reviews
As it turns out, ESLint, Prettier, and other code checks are rarely done manually, so it would be nice to have mandatory code checks before committing to Git to prevent 💩 from sneaking into the repository. Husky, Lint-staged combinations are needed.
husky
Git hooks which enable you to execute scripts at specified times, such as before or after a commit or push trigger.
- ESLint checks code quality
- 4. Automate code formatting fixes by Prettier
- right
Commit Message
Do normalization check - Automate testing of project code
It is worth noting that some of the hook scripts are automatically generated and customized in a Git repository under.git/hooks, but it is not very friendly to modify them directly, so Husky provides a simple and easy-to-use Git hooks configuration, using the recommended husky@7, Migrate from V4 to v7: Migrate from v4 to v7
First, install dependencies:
npm i -D husky
Copy the code
Then launch Git hooks:
npx husky install
Copy the code
To automatically start Git hooks after installation, package.json requires the prepare script:
{
"scripts": {
"prepare": "husky install"}}Copy the code
With that done, you can create a hook using Husky:
npx husky add .husky/pre-commit "npm test"
Copy the code
Open./husky to see that a pre-commit script has been generated, which will execute NPM test before git commit:
#! /bin/sh . "$(dirname "$0")/_/husky.sh" npm testCopy the code
Lint-staged
Now that we have implemented listening for Git hooks, we need to automatically fix Prettier code and ESLint check it from Lint-staged hooks before committing. If you find a file that does not conform to the code specification, exit commit.
Lint-staged code is checked only within Git staging (Git Add code), not the whole thing, and code formatted from Prettier will automatically be added into the COMMIT.
First install dependencies:
npm i -D lint-staged
Copy the code
Then configure it in package.json:
{
"lint-staged": {
"*.{js,jsx,ts,tsx}": ["prettier --write"."eslint"]."*.{css,less,scss}": "prettier --write",}}Copy the code
Js,.jsx,.ts,.tsx files where prettier is formatted and eslint is executed. Prettier is enough for a style file.
Don’t forget to add lint-staged calls to.husky/pre-commit:
#! /bin/sh . "$(dirname "$0")/_/husky.sh" npx lint-stagedCopy the code
conclusion
By the end of this article, you should have a general understanding of the overall code specifications and constraints of the project, and be able to put these areas into practice:
- Know the simple technical principles of ESLint and Prettier, configure ESLint and Prettier, and use unified specifications discussed by the team as configuration packages.
- Understand the difference between ESLint and Prettier and use them together.
- Learn about Git hooks and use husky to listen on executing hooks.
- Prettier, ESLint checks code in executing Git hooks