preface
There are three reasons why you should do code quality checks:
- Some common code problems, if the compile or run time can not be found in time, the syntax problems in the code will directly lead to compile or run time errors, affecting the development efficiency and code quality;
- Unified code habits. Every team or individual will have some code specifications or code habits. In order to facilitate later maintenance and reading, the code we write also needs to conform to certain format specifications:
- The blank space;
- Uniform indent;
- Naming convention;
- Ensure online code quality. In versioning, we need to automate some code reviews before we commit or release to make sure that our code meets the final version requirements.
Common problems in front end code
Writing style
Simply put, code that is too arbitrary is hard to read, and hard to read code is sometimes worse than starting over.
// bad
var once
, upop
, aTime;
// good
var once,
upon,
aTime;
// bad
var hero = {
firstName: 'Bob'
, lastName: 'parr'
, heroName: 'Mr.Incredible'
, superPower: 'strength'
};
// good
var hero = {
firstName: 'Bob'.lastName: 'parr'.heroName: 'Mr.Incredible'.superPower: 'strength'
};
Copy the code
Code specification
Code that doesn’t adhere to coding standards and conventions can make you want to stop reading it, or even lose your sense of meaning. Some people think that this problem is only for junior programmers, but it is not. Some students who have worked for two or three years still write code like this. For some individual self-study awareness is not positive enough, no team normative guidance of programmers, it is easy to code format non-standard problems.
Lint will look at the source code to find:
- Format problem;
- Non-compliance with coding standards and practices;
- Locate logic errors that may exist in the program.
Code Lint is dynamically monitoring side-write errors so that we can write high-quality code. Lint, unlike Prettier or Format, tells you only about errors or irregularities in code, while Format is used to change the Format.
ESlint introduction
ESlint is a linting utility for JavaScript.
ESlint does not rely on specific coding conventions, and users are free to enable or disable individual coding conventions. In this sense, one of its main features is its high degree of customisability.
Users can set encoding standards flexibly by defining primitive rules, which are the default encoding rules available in Elint.
The core concept
-
Configuration files:.eslintrc,.eslintrc.js,.eslintrc.yml
-
Rules:
- “Off” or 0: turns off the rule;
- “Wran” or 1: turns on the rule with a warning level error: WARN (does not cause the program to exit);
- “Error” or 2: turns on the rule, using the error level error: ERROR (when the shell fires, the program exits).
Here’s an example:
{ "rules": {"semi": ["error"."never"]."quotes": ["error"."single"]}}Copy the code
Here’s an example:
{ "rules": {"semi": ["2"."never"]."quotes": ["2"."single"]}}Copy the code
-
Extends: Uses a package provided by someone else, such as Google:
{ "extends":"google" } Copy the code
-
Plugins: The default rules provided by ESlint cover the basic rules, but there is a wide range of things that JavaScript can use. Therefore, you might want the rule not to be in the default rule. In this case, you can develop your own separate rules in ESlint. To allow third parties to develop their own rules, ESlint allows the use of plugins. If you search for eslint-plugin-* in NPM, you can find a number of custom plugins provided by third parties. If ESlint’s default rules do not provide rules to use, it is recommended that you look for plug-ins.
Like shareable configuration, it is easy to set up. For example, if you want to perform static analysis of React code, you can install a plug-in named eslint-plugin-react and use the following Settings to perform React syntactically specific static analysis.
{ "extends":"google"."plugins": ["react"]."rules": {"semi": [2."never"]."quotes": [2."single"]}}Copy the code
Starting and installation
Used in projects
// --dev installs esLint in the devDependencies attribute of the package.json file, which means that the package will be used in the knowledge development phase, but will not be needed for launch
yarn add eslint --dev
Copy the code
Added package.json script:
"scripts": {
"lint": "eslint app.js"."lint:create": "eslint --init"
},
Copy the code
Then use the run command:
yarn lint:create
Copy the code
Use globally
yarn global add eslint
eslint --init
Copy the code
The generated.eslintrc.js file exports an object containing env, extends, parserOptions, plugins, and rules properties:
- Env: specifies the environment in which the script is run. Each environment has a specific set of predefined global variables (e.g. Nodejs, browser, commonJS, etc.).
- ParserOptions: Used to specify which JavaScript language options you want to support:
- EcmaVersion: the default is 3,5 (default). You can use 6, 7, 8, or 9 to specify which version of ECMAScript you want to use. You can also specify 2015 (same as 6), 2016 (same as 7), 2017 (same as 8) or 2018 (same as 9) as the version number named by the year;
- SourceType: Set this to “script” (default) or “Module” (if your code is ECMAScript).
- Globals: Additional global variables that the script needs to access when executing code;
- Rules: Enables certain rules and sets the level of rules.
.eslintignore
This can be created at the project root to tell ESlint to ignore certain files or directories. The equivalent of.gitignore is plain text.
How to use ESlint
After you’ve set the.eslintrc.js configuration file in the steps above, you can run ESlint in the project directory and check your js file:
yarn lint index.js
Copy the code
Vscode uses ESLint to save automatic formatting
-
Add.eslintrc.js files to the project and directory
// https://cn.eslint.org/docs/rules/ // /* * "off" or" 0 ", do not enable this rule * "warn" or" 1 ", there is a warning * "error" or" 2 ", there is an error */ module.exports = { root: true.// This is used to tell ESLint that the current configuration file cannot be found at the parent level env: { // Ring configuration such as "browser": true, node: true, node: true,},extends: [ 'google',].rules: { 'array-callback-return': 1.// Whether to allow omission after return "arrow-parens": ["error"."as-needed"].// The arguments to the arrow function may not use parentheses 'consistent-return': 0.// Requires that the return statement either always specify the returned value or not 'camelcase': 0.// Mandatory hump naming 'eqeqeq': 0.// Force congruences (=== and! = =) 'func-names': 0.// Function expressions must have names "global-require": 0.// Cancel validation of require so that require can be used to load relative paths of images "import/no-unresolved": 0.// Disable automatic path resolution to enable alias path setting 'import/extensions': 0.// Cancel validation of file extensions 'indent': 'off'.// Indent style (enforce consistent indent) "linebreak-style": 0.// Unvalidate the newline character \n or \r\n () 'max-len': 0.// Maximum length of a string "no-unused-vars": 1.// Disallow unused variables "no-redeclare": 1.// Disallow multiple declarations of the same variable 'no-use-before-define': 1.// Disallow using variables before they are defined "no-unused-expressions": 0.// Allow unused expressions to support the code form of a && a() 'no-restricted-syntax': 1.// Disable specific syntax 'no-plusplus': 1.// Do not use ++, -- 'no-underscore-dangle': 0.// Underline is allowed in identifiers 'no-param-reassign': 0.// Disable reassignment of function parameters 'no-nested-ternary': 0.// Disallow nested ternary expressions 'no-else-return': 0.// Disallow else blocks after return statements in if statements 'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off'.'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'.'no-shadow': [1, { // A variable in an outer scope cannot have the same name as a variable or parameter in the scope it contains "allow": ["resolve"."reject"."done"."cb"]}],'prefer-rest-params': 1.// Require remaining arguments instead of arguments 'prefer-arrow-callback': 0.// Requires the callback function to use the arrow function 'prefer-const': 1./ / the preferred const "semi": false.// Use a semicolon, default true "singleQuote": true.// Use single quotes, default false(invalid in JSX, default is double quotes) "tabWidth": 4.// TAB indent size, default is 4 'template-curly-spacing': 'off'.// Requires or disallows the use of Spaces around embedded expressions in template strings }, parserOptions: { parser: 'babel-eslint',}};Copy the code
-
Add eslint to vscode.
-
Settings are automatically formatted according to ESLint rules when saved. You can find settings.json in Preferences — Settings
Add the following configuration:
```JavaScript "editor.codeActionsOnSave": { "source.fixAll.eslint": true }, "eslint.format.enable": true ``` Copy the code
Take a look at esLint’s detailed instructions for using the new version of the configuration:
This will automatically format the files when you save them after configuration.
ESLint and Prettier are used in Vue projects
While ESLint does some formatting checks on our code (such as semicolons, single and double quotes), it doesn’t always work the same way, and we still need the tool Prettier. It doesn’t care if your syntax is correct, it only cares if your code format is correct, such as using single quotes, using semicolons at the end of statements, etc. It can be used to detect not only JavaScript code format, but also vue files, react files, etc.
Go deeper into VSCode configuration
For most of you, when you start the plugin, VSCode is still not highlighted. Because you need to continue to configure the relevant parameters in VSCode.
"eslint.probe": [
"javascript"."javascriptreact"."typescript"."typescriptreact"."html"."vue"."markdown"].Copy the code
Eslint. probe specifies the language type that the eslint plugin needs to verify. After adding the language, VSCode will correctly highlight the incorrect syntax in the code editor and print the error message in the window. If you need to add [” HTML “, “vue”] here to enable ESlint detection in the.vue single file, these two options need to be supported by the eslint-plugin-vue eslint-plugin-html package. Needs to be installed into the project.
Eslint plugins start with eslint-plugin- and can be omitted when used. For example, we detect the.vue file above using the eslint-plugin-vue plug-in; Note that when you configure eslint-plugin-vue, if you only configure “plugins”: [“vue”], the vue file will still fail to parse.
This is because neither the default espree nor babel-esLint parsers can parse the contents of the template in.vue; The eslint-plugin-vue plugin relies on the Vue-eslint-parser parser parser, which only parses template content, not JS content in script tags. Therefore, we need to specify the following parser:
{
"extends": ["eslint:recommended"]."plugins": ["vue"."html"]."parser": "vue-eslint-parser"."parserOptions": {
"parser": "babel-eslint"."ecmaVersion": 12."sourceType": "module",}}Copy the code
Parseroptions. parser can only be used with one outer parser, and we can’t write any more than the vue-eslint-parser parser. So what vue-eslint-Parser does is pass another parser option in the parser option to handle the JS content in the script.
Example Enable the formatting of prettier
With this option enabled, VSCode can now correctly display ESlint error messages. Next, enable prtTier formatting. While prettier is a tool for checking code formatting, ESlint is a tool for checking syntax. Maintaining both configurations can be cumbersome for a project, so ESlint provides support directly in the form of plug-ins.
The installation
To use the Prettier, of course, have to install it first, and then also need to install eslint – plugin – Prettier.
To prevent the Prettier and ESLint formatting from conflicting, you must also install eslint-config-prettier to disable code formatting in ESLint.
yarn add -D eslint
yarn add -D eslint-plugin-prettier
yarn add -D eslint-config-prettier
Copy the code
The.prettierIgnore and.eslintignore files can be used to add files or folders that do not need to be formatted. Ignore these files when pretticizing code bugs.
configuration
Here’s what the configuration file for adding the Prettier plug-in looks like in ESLint:
{
plugins: ["prettier"].rules: {
prettier/prettier: "error"}}Copy the code
A recommended configuration for eslint-plugin-prettier on GitHub:
{
extends: ["plugin:prettier/recommended"]}Copy the code
We can create an.prettierrc.json file in our project:
{
/ / stern commas
"trailingComma": "es5".// Indent length
"tabWidth": 4.// Semicolon at the end of the code
"semi": false./ / single quotation marks
"singleQuote": true.// Maximum length of a single line of code
"printWidth": 100.// Parentheses for object literals
"bracketSpacing": true.// Add parentheses to the arrow function arguments
"arrowParens": "always",}Copy the code
Here are a few of the common ones. You can find more configuration rules in the official website options Configuration.
This will fix the code, but if we run into another, opinionated extension, such as eslint-config-standard, which has its own code style; If “Prettier” is used for formatting, “standard” does not work. “Prettier” : if “standard” automatically fixes an Prettier, “Prettier” reports an error.
We can use the last of the extends features to override the previous extension. We can disable some rules for prettier by configuring eslint-config-prettier at the end of the extends:
{
extends: ["standard"."plugin:prettier/recommended"]}Copy the code
This is then configured in setting.json
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"
"editor.codeActionsOnSave": {
"source.fixAll": true
("source.fixAll.eslint": true)
}
}
Copy the code