This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021
Common Problems in front-end code (Why Lint)
Writing style
Must have taken over other code students, how many have some experience. To put it simply, code that is too arbitrary is too much for ocD to tolerate, and code that is difficult to read and understand is sometimes as good as tearing it down and starting from scratch.
// bad
var once
, upon
, 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
What kind of code is low quality or high quality? Good code can make you feel like you’re reading a novel, bad code can make you look at it and not want to continue, or even look at it for a while.
One might think that this is a problem only for junior programmers, but it is not, and it is still true for some code written with two or three years of experience. For some individuals whose self-learning awareness is not active enough and there is no normative guidance from the team, it is easy to get used to the situation of “learning for half a year and then repeating for three years without any progress”.
Lint will use the source code to find:
-
Format problem
-
Non-compliance with coding standards and practices
-
Pinpoint possible logic errors in the program
Highly coupled
This kind of problem is actually quite common. Hundreds of lines for a function, thousands of lines for a file, dozens of methods for a class, arbitrary definition of method parameters, no comments, no clear semantics for method and variable names, data modifications and changes interspersed in various methods, and so on. It’s really hard to understand the logic of the code, and you’ll have to read it line by line (and maybe curse at the same time).
The main reason lies in the lack of basic knowledge, coding experience and consciousness of the developer.
In fact, the common open source coding specifications will address this situation. My advice is to brush up on object-oriented programming, functional programming, data structures, common design patterns, take a look at the various open source coding specifications and try to really understand them. When you look back at code from a month ago and see that you can improve or refactor to make the code logic clearer, it shows that you are growing and improving.
It is common to see this kind of question: new project is being selected, vue. js, React, Angular three framework is suitable? In fact, team development members are experienced with all of these things, and any of them can be; If most of the team members are not experienced in front-end development or the staff is not stable, vue.js is the best choice. Why? Because it’s simpler, simpler, and easier to learn. Vue.js uses hooks such as prop, data, computed, Method and Watch to limit coding methods and styles to a certain extent, so that code written by junior developers is not too ugly, which is one of the reasons why vue. js is gaining popularity in the community.
(Def: Lint Code)
So what is code quality monitoring?
Lint or Linter is a tool or procedure for analyzing source code to flag errors written during programming (code, style, build).
Lint, or a linter, is a tool that analyzes source code to flag programming errors, bugs, stylistic errors, and suspicious constructs.[1] The term originates from a Unix utility that examined C language source code.[2]
Lint dynamically monitors code writing errors so that we can write high-quality code.
As opposed to Prettier or Format, which modifies the Format, Lint only tells you what is wrong or nonconforming in code.
How to Monitor code quality (How to Lint)
In order to unify the team’s code specification, it is necessary to introduce tools to restrict it in addition to a specification. While tools do not fully implement the rules of the specification, they can at least mitigate some of the code inconsistency.
In contrast to the back end, the quality check of the front-end code specification involves HTML, CSS, Javascript, and now SCSS, ES5, JSX, React, Vue, Angular, etc.
Common code quality Lint tools:
HTML / tpl: HTMLHint
CSS / SCSS: StyleLint
JS / JSX: ESLint
Comparison of three common Js checking tools
There are three common JS validators you can use, but how do you choose which one to use? Let’s take a look at the features, advantages and disadvantages of these four popular scenarios: JSLint, JSHint, ESLint.
Several tools work in the same basic way. Has a set of rules for users to analyze and report errors in JS files. All can be installed via NPM. Can be used from the command line, as an IDE plug-in, or integrated into an editor. Note Configuration is supported.
JSLint
JSLint is the oldest of these tools. Douglas Crockford developed this tool in 2002, based on his experience, to force the use of the essence of the JS language. JSLint can be a good tool if you agree with these essentials.
The downside of JSLint is that it cannot be configured or extended. You simply cannot disable the required features, and many lack documentation. The official documentation is quite unfriendly, lacking information on how to integrate it into editing, for example.
advantages
- After the parameters are configured, you can use them directly
disadvantages
- JSLint does not have a configuration file, which would be a problem if you wanted to change parameter Settings
- With limited configuration options, many rules cannot be disabled
- Cannot add personalization rules
- There are no documented rules
- It is difficult to know which rule causes the error
JSHint
JSHint was developed as a configurable version of JSLint. You can configure each rule and put it in a configuration file so that it can be used easily in large projects. JSHint has good documentation for each rule, so you know exactly what each rule does. Integrating it into the editor is also simple.
One minor drawback of JSHint is its loose default configuration. That is, you have to boot it up before you can make it usable. JSHint is more difficult than ESLint to determine which rule user turns error messages on or off.
advantages
- Most of the parameters can be configured
- Support configuration files, easy to use in large projects
- It already supports required class libraries like jQuery, QUnit, NodeJS, Mocha, etc
- Supports basic ES6
disadvantages
- It is difficult to know which rule produces an error
- There are two types of options: mandatory options and loose options. This makes the configuration a bit confusing
- Custom rules are not supported
ESLint
ESLint is a relatively new tool. It is designed to be easy to extend, has plenty of custom rules, and is easy to install via plug-ins. It gives the exact output and includes the rule name so you know which rule caused the error.
The ESLint documentation is somewhat confusing. Rules are easy to find and grouped into logical groups, but configuration guidelines can get confusing in some places. However, it can provide links in one place to edit integrations, plug-ins, and samples.
advantages
- Flexibility: Any rule can be turned on or off, and some rules have additional configurations
- Easy to extend and available plug-ins on demand
- Easy to understand output
- Contains rules not available in other checkers, making ESLint more useful for error checking
- ES6 support, JSX support tools
- Supports custom reports
disadvantages
- You need some configuration
- Slow speed
JSCS has been incorporated into ESlint
To sum up:
classification | JSLint | JSHint | ESLint |
---|---|---|---|
The initial configuration | There are | There are | configurable |
The custom | Command line, limited | configurable | configurable |
The configuration file | no | is | is |
ES6 | is | is | is |
JSX | no | is | is |
Execution efficiency | high | In the | low |
Output friendliness | low | In the | high |
Stars | 3.3 k. | 8.2 k. | 14.2 k. |
Introduction to Lint
Lint is a tool that analyzes source code and notifies users of errors or discrepancies with team coding conventions. It can also fix errors automatically in some cases.
While many versions of Lint have been developed for different languages, some people may have encountered the following problems.
-
This is my first time coding in this language. What is considered the general coding style of this language?
-
I’m using the default Settings for Lint, but the error verification process is too strict.
I want to change the Settings, but will it be easier to ignore certain errors by changing the Settings?
Even for a single language, various coding conventions have been proposed. So, especially in the first place, it can be difficult to determine which coding conventions are best followed.
So let’s take a look at Lint Settings on common open source software to see what Settings and coding conventions are being used.
ESLint
ESLint is a JavaScript linting utility.
ESLint does not depend on specific coding conventions, and users are free to enable or disable individual coding conventions. In this sense, one of its key features is its high degree of customizability.
Users have the flexibility to set coding standards by defining raw rules, which are the default coding rules available in ESLint. In addition, well-known coding conventions shared by third parties, such as “Google JavaScript Style Guide” or “Airbnb JavaScript Style Guide” can also be reused.
You can even enable/disable specific rules for specific files while following these coding conventions.
If you don’t know the setup to get started, refer to the official “Getting started” guide provided by ESLint to use the suggested coding conventions.
Key Concepts:
-
Configuration file:
.eslintrc
,.eslintrc.js
,.eslintrc.yml
-
Rules:
- Or “off”
0
– Close rule - Or “warn”
1
– Enable the rule to use warning level errors: WARN (will not cause the program to exit) - Or “error”
2
– Enable the rule, using error level error: error (when triggered, the program will exit)
Look at an example:
{ "rules": { "semi": ["error"."never"]."quotes": ["error"."single"]}}Copy the code
It can also be written as:
{ "rules": { "semi": [2."never"]."quotes": [2."single"]}}Copy the code
- Or “off”
-
Extends:
Use packages provided by others, such as Google
{ "extends":"google",}Copy the code
By using the above instructions, users can easily use the coding conventions in the Google JavaScript Style Guide without having to write Settings from scratch.
-
Plugins:
ESLint provides default rules that cover basic rules, but JavaScript can be used in a very wide range of ways. Therefore, you might want rules not to be in the default rules. In this case, you can develop your own separate rules in ESLint. To allow third parties to develop their own rules, ESLint allows plug-ins. If you search for eslint-plugin- * in NPM, you can find a number of custom plugins provided by third parties.
If ESLint’s default rule does not provide the rule you want to use, it is recommended that you look for the plug-in.
Like the shareable configuration, it is easy to set up. For example, if you want to perform static analysis on React code, you can install a plugin called eslint-plugin-react and use the following Settings to perform static analysis specific to the React syntax.
{ "extends": "google"."plugins": [ "react"]."rules"": {"semi": ["error","never"]."quotes": ["error","single"]}}Copy the code
Start-up and installation
-
Use it in your project
// The NPM init directive generates package.json files in the project root directory. npm init // --save-dev installs esLint into the devDependencies property of the package.json file, which means that the package is only used during development and is no longer needed when it goes live. npm install eslint --save-dev Copy the code
- use
npm run
Add package.json script, or use the NPX command
"scripts": { "lint": "eslint src"."lint:create": "eslint --init" } Copy the code
Then use the run command:
npm run lint Copy the code
- Direct use of
npx
Command:
NPX eslint --init // or./node_modules/.bin/eslint --initCopy the code
- use
-
Use globally
npm install -g eslint Copy the code
ESLint initialization
The configuration method uses the esLint –init method
➜ NPX eslint --init? How would you like to use ESLint? (Use arrow keys) To check syntax only ❯ To check syntax and find problems To check syntax, find problems, and enforce code style ? Whattypeof modules does your project use? ❯ JavaScript modules (import/exportCommonJS (require/exports) None of these // can be configured for your development project? Which framework does your project use? React vue.js ❯ None of these // can be configured to run the code in a browser or Node environment? ? Where does your code run? ❯◉ Browser ◉ Node // Where is the most cache? What formatdo you want your config file to be in? ❯ JavaScript YAML JSON // Successfully created the configuration file? What formatdo you want your config file to be in? JavaScript
Successfully created .eslintrc.js file in /Users/itheima/Downloads/Demo
Copy the code
Configuration file.eslintrc.js:
Deprecated usage:.eslintrc, esLint uses the configuration order:.eslintrc.js >.eslintrc.yaml >.eslintrc.yml >.eslintrc.json >.eslintrc > package.json
. Eslintrc. Js file:
module.exports = {
"env": {
"browser": true."es6": true."node": true
},
"extends": "eslint:recommended"."globals": {
"Atomics": "readonly"."SharedArrayBuffer": "readonly"
},
"parserOptions": {
"ecmaVersion": 2018."sourceType": "module"
},
"rules": {}};Copy the code
Let’s look at the YAML file configuration:
env:
browser: true
es6: true
node: true
extends: 'eslint:recommended'
globals:
Atomics: readonly
SharedArrayBuffer: readonly
parserOptions:
ecmaVersion: 2018
sourceType: module
rules: {}
Copy the code
This file exports an object containing the env, extends, parserOptions, plugins, and rules attributes:
-
Env: specifies the running environment of the script. Each environment has a specific set of predefined global variables (e.g. Nodejs, Browser, CommonJS, etc.).
-
ParserOptions: Specifies the JavaScript language options you want to support
-
EcmaVersion – the default is set to 3,5 (the 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) with the version number named after the year.
-
SourceType – Set to “script” (default) or “module” (if your code is an ECMAScript module).
-
ecmaFeatures Copy the code
– This is an object that represents additional language features you want to use:
globalReturn
– Allows use in global scopereturn
statementsimpliedStrict
– Enable globalstrict mode(ifecmaVersion
Is 5 or higher)jsx
– to enableJSX
-
-
Globals: Additional global variables that footsteps need to access when executing code.
-
Rules: Enables certain rules and sets the level of rules.
-
Extends: Extends the default rule, either using Airbnb or the Standard rule.
.eslintignore
It can be created in the project root to tell ESLint to ignore certain files or directories. The equivalent of.gitignore is a plain text file. For example,
# comment, ignore the file node_modules**/.jsbuildCopy the code
Common eslintignore content:
node_modules/* **/node_modules/* dist/* /build/** /coverage/** /docs/** /jsdoc/** /templates/** /tests/bench/** /tests/fixtures/** /tests/performance/** /tmp/** /lib/rules/utils/unicode/is-combining-character.js test.js ! .eslintrc.jsCopy the code
How to use ESLint
-
Local usage:
If you want ESLint to be part of your project build system, we recommend installing it locally. You can use NPM:
$ npm install eslint --save-dev Copy the code
Next you should set up a configuration file:
$ ./node_modules/.bin/eslint --init Copy the code
After that, you can run ESLint in your project root directory:
$ ./node_modules/.bin/eslint yourfile.js Copy the code
With locally installed ESLint, any plugins or shareable configurations you use must also be installed locally.
-
The global
If you want ESLint to work with all your projects, we recommend that you install ESLint globally. You can use NPM:
$ npm install -g eslint Copy the code
Next you should set up a configuration file:
$ eslint --init Copy the code
After that, you can run ESLint in any file or directory:
$ eslint yourfile.js Copy the code
ESlint configuration is commonly used
Specification for ESLint:
Standard: github.com/standard/es…
The specific address: eslintrc.json
Reality: github.com/airbnb/java…
-
Comma in the comma
rules: { "comma-dangle": ["error"."never"],}Copy the code
Bad:
var foo = { a: '123'.b: '321'.// wrong error } Copy the code
Right:
var foo = { a: '123'.b: '321' } Copy the code
-
Quotes quotes
-
Semi semicolons
-
A blank line
-
Hump named
-
Log output
-
As a judge
-
Redundant variables
-
The blank space
- The space after the keyword
- The space after the function name
- The indentation
Configuration in the IDE
- Here is the plug-in configuration in vscode:
Configuration file:
"eslint.alwaysShowStatus": true."eslint.autoFixOnSave": true."editor.formatOnSave": true."eslint.validate": [
"javascriptreact",
{
"language": "html"."autoFix": true
},
{
"language": "javascript"."autoFix": true}]."eslint.options": {
"plugins": ["html"]},Copy the code
Quick Fix configuration:
Open “editor.formatOnSave”: true and turn on eslint.validate as configured above, or set it in the UI.
- Configuration in Webstorm:
Configure the Preferences
It’s much smarter than vscode.
Actual vUE project configuration
ESlint configuration files:
module.exports = {
root: true.env: {
node: true,},extends: [
'plugin:vue/essential'.'@vue/standard',].rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off'.'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'.semi: ['error'.'never'],},parserOptions: {
parser: 'babel-eslint',}}Copy the code
VSCode plug-ins to install:
- Vue (highlighting syntax)
- Vetur (Formatting, code specification)
- Vue Peek (Component Jump)
- Vue Beautify (VUE Formatting)
- Vue VSCode Snippets and Vue Snippets(code prompts)
- Prettier(formatting co-formatting with Vetur above)
Vscode configuration formatting:
"eslint.validate": [
"javascript"."javascriptreact",
{
"language": "html"."autoFix": true
},
{
"language": "vue"."autoFix": true}]."vetur.format.defaultFormatter.js": "prettier-eslint".// prettier
"prettier.trailingComma": "es5"."prettier.semi": false."prettier.jsxSingleQuote": true."prettier.singleQuote": true."prettier.eslintIntegration": true.Copy the code
Emmet configuration:
"emmet.syntaxProfiles": {
"vue-html": "html"."vue": "html"
},
Copy the code
In vue-CLI tools, you can use NPM run Lint:
➜ NPM run lint > [email protected] lint /Users/itheima/vue-demo > vue-cli-service lint DONE No lint errors found!Copy the code
To execute the vue CLI configured Lint script:
"scripts": {
"serve": "vue-cli-service serve"."build": "vue-cli-service build"."lint": "vue-cli-service lint"
},
Copy the code
Recommended use of vscode plug-ins:
Vue, Vetur, Vue Peek, vue-beautify
React Project configuration
Create a react project with create-react-app:
npx create-react-app my-app
cd my-app
npm start
Copy the code
If the NPX command is not used, install create-react-app globally. Run NPM install -g create-react-app
Next, install esLint-related dependencies:
"devDependencies": {
"eslint": "^ 5.16.0"."babel-eslint": "^ 10.0.2"."eslint-plugin-html": "^ 6.0.0"."eslint-plugin-react": "^ 7.14.2"
}
Copy the code
Configure ESLint, or use esLint –init to initialize:
module.exports = {
"env": {
"browser": true."commonjs": true."node": true."es6": true
},
"extends": [
"eslint:recommended"."plugin:react/recommended"]."globals": {
"Atomics": "readonly"."SharedArrayBuffer": "readonly"
},
"parserOptions": {
"ecmaFeatures": {
"jsx": true."arrowFunctions": true."classes": true."modules": true."defaultParams": true
},
"ecmaVersion": 2018."sourceType": "module"
},
"plugins": [
"react"]."rules": {},"settings": {
"react": {
"pragma": "React"."version": "latest",}}};Copy the code
Note the following configurations:
- Install plug-in:
eslint-plugin-react
- configuration
extends
:"plugin:react/recommended"
- configuration
settings
Someone whose configuration:
npm --save-dev install eslint-config-airbnb eslint-plugin-import eslint-plugin-jsx-a11y babel-eslint
Copy the code
There are three dependencies:
- eslint-config-airbnb
- eslint-plugin-import
- eslint-plugin-jsx-a11y
- Babel-eslint
Modify project configuration:
module.exports = {
"env": {
"browser": true."commonjs": true."node": true."es6": true
},
// There is a change here
"extends": [
"eslint:recommended"."plugin:react/recommended"."plugin:import/errors"."plugin:jsx-a11y/recommended"."airbnb"]."globals": {
"Atomics": "readonly"."SharedArrayBuffer": "readonly"
},
"parser": "babel-eslint"."parserOptions": {
"ecmaFeatures": {
"jsx": true."arrowFunctions": true."classes": true."modules": true."defaultParams": true
},
"ecmaVersion": 2018."sourceType": "module"
},
// There is a change here
"plugins": [
"react"."jsx-a11y"."import"]."rules": {
// Here you can add jsX-ally's custom rules related to import
},
"settings": {
"react": {
"pragma": "React"."version": "latest",}}};Copy the code
StyleLint
Liverpoolfc.tv: stylelint. IO /
-
Install dependencies:
npm install -D stylelint-config-recommended stylelint-config-standard // yarn yarn add stylelint-config-recommended stylelint-config-standard -D Copy the code
-
Configuration to ignore
//.stylelintignore Ignores the files checked by stylelint/SRC /**/*.cssCopy the code
-
.stylelintrc.js File configuration
module.exports = { "extends": ["stylelint-config-recommended"."stylelint-config-standard"]."rules": { "indentation": 2}}Copy the code
-
Vscode configuration
Install the Prettier + stylelint plug-in to format code easily.
Configuration file:
"[SCSS]": {"editor.formatOnSave": true}, // open SCSS validate configuration "SCSS. Validate ": true,Copy the code
HTMLHint
Liverpoolfc.tv: htmlhint. IO
Making: github.com/htmlhint/HT…
-
Install dependencies:
npm install htmlhint --save-dev // yarn yarn add htmlhint -D Copy the code
-
Configuration to ignore
//.stylelintignore Ignores the files checked by stylelint/SRC /**/*.cssCopy the code
-
Htmlhintrc file configuration
/** The tag name must be lowercase the attribute name must be lowercase the attribute value must be in double quotes The attribute value must not be null the attribute value must not be duplicated Doctype must be the first line of an HTML document Tags must pair tags must be self-enclosed Special characters must ID attribute must be unique SRC attribute must not be null The title attribute must appear in the tag the IMG tag must contain the Alt attribute Doctype must be HTML5 ID and Class naming conventions must be consistent Should not use style tags should not use inline styles should not use inline scripts Spaces and tabs must not be mixed before the line ID And Class must not be used. Keyword href must be absolute path or relative path. Attribute values must not be used with unsafe characters { "tagname-lowercase": true."attr-lowercase": true."attr-value-double-quotes": true."attr-value-not-empty": false."attr-no-duplication": true."doctype-first": true."tag-pair": true."empty-tag-not-self-closed": true."spec-char-escape": true."id-unique": true."src-not-empty": true."title-require": true."alt-require": true."doctype-html5": true."id-class-value": "dash"."style-disabled": false."inline-style-disabled": false."inline-script-disabled": false."space-tab-mixed-disabled": "space"."id-class-ad-disabled": false."href-abs-or-rel": false."attr-unsafe-chars": true."head-script-disabled": true } Copy the code
-
Vscode configuration
Install Prettier, HTMLHint plug-in to format code easily.
User profile:
"[HTML]": {"editor.defaultFormatter": "esbenp.prettier-vscode"}, // Open the VALIDATE configuration of SCSS "files.associations": { "*.ext": "html" },Copy the code
e2e test
Two types of testing are typically performed on Web applications: unit testing and end-to-end (E2E) testing.
Unit testing
The idea of using “units” in testing is to break down the code into widgets that are easy to test. Typically, a unit is a single function, but it can also be a class or even a complex algorithm.
A key concept of unit testing is that a given input to a function should always produce the same output.
For example, if we have a function that adds two numbers to the call, add we can write a unit test to ensure that the particular pair of numbers we provide as arguments always returns the output we expect.
add.spec.js
// Function we want to test
const add = (x, y) = > x + y;
// Unit test
test("should add two numbers".() = > {
const result = add(2.3);
expect(result).toBe(5);
});
Copy the code
Any time we run the test and it does not equal 5, we can draw an error that has been entered into our code.
Component test
In most vue.js applications, functions don’t really represent the atomic makeup of the application. Sure, we can unit test our methods, but what we really care about is the generated HTML.
Therefore, the unit in the vue.js app test is a component rather than a function.
How do we test components? Take this as an example:
displayGreeting.js
export default {
template: `<div>Hello, {{ name }}</div>`.props: ['name']};Copy the code
As mentioned earlier, for a given input (pillar, in this case), the unit test must return consistent output (text content, in this case).
Using libraries like Vue Test Utils, we can install Vue components in memory and create a “wrapper” object. We can then query the wrapper to assert the rendered HTML.
displayGreeting.spec.js
import displayGreeting from "./displayGreeting.js";
test("displays message".() = > {
const name = "Michael";
const wrapper = mount(displayGreeting, { propsData: { name } });
expect(wrapper.text()).toBe(`Hello, ${name}`);
});
Copy the code
Unit testing benefits:
- The tests ran quickly
- The tests are precise, allowing you to identify the exact problem
Unit testing disadvantages:
- Writing tests for every aspect of your application can be time-consuming
- Even if the unit tests pass, the entire application may not work properly
What is the E2E Test?
E2e Test (End to End Test) is a functional test. Unlike unit testing, you don’t break the application down into smaller parts for testing – you test the entire application.
E2e tests interacting with your application just like a real user. For example, you could write an E2E test:
- Load your website
- Click the “Register” link
- Provide some valid details for the input in the registration form
- Click Register Button.
This test should be passed if the authentication token is stored in a Cookie and the application is redirected to the profile page.
E2E Tests the advantages
- You can test many things implicitly at once
- E2e testing ensures that you have a working system
Disadvantages of e2E testing:
- Slow running – usually takes 5 or 10 minutes to run a site
- Tests are fragile – an insignificant change, such as changing component logic, would require a redesign of the E2E Test
- The test was unable to pinpoint the cause of the failure
So, the main business process might write E2E, but on a much smaller scale, with the main purpose of:
- Facilitate the presentation of business processes to the PM
- Facilitate regression after Bug modification
This section describes the E2E Test tool
Cypress
-
Install & desktop applications
npm install cypress --save-dev Copy the code
Or download the desktop app directly:
download.cypress.io/desktop
-
Usage:
./node_modules/.bin/cypress open // npx npx cypress open // yarn yarn run cypress open Copy the code
Or add package.json:
{ "scripts": { "cypress:open": "cypress open"}}Copy the code
Use the NPM command: NPM run cypress:open
Complete explanation of ESLint file configuration properties
/* * ESLint JSON files allow JavaScript comments, but gist doesn't look very good, so I changed the.json file suffix to.js */
/* * ESLint configuration file priority: *.eslintrc.js(outputs a configuration object) *.eslintrc.yaml *.eslintrc.yml *.eslintrc.json (JSON files in ESLint allow JavaScript style comments) * .eslintrc (either JSON or YAML) * package. JSON (create an eslintConfig property in package. JSON and define your configuration there) */
/* * You can tell ESLint to ignore specific files and directories by creating an.eslintignore file in the project root *. The eslintignore file is a plain text file where each line is a glob pattern indicating which paths should be ignored for detection */
{
//ESLint uses Espree as its parser by default
// Babel-esLint is also the most used parser
"parser": "espree".// Parser Is the parameter used to parse code
"parserOption": {
// Specify the version of ECMAScript to use, default 5
"ecmaVersion": 5.// Set to script(default) or module (if your code is an ECMAScript module)
"sourceType": "script".// This is an object that represents additional language features you want to use. All options default to false
"ecmafeatures": {
// Allow the use of return statements in the global scope
"globalReturn": false.// Enable global strict mode (strict mode)
"impliedStrict": false./ / enable JSX
"jsx": false./ / to enable support for experimental objectRest/spreadProperties
"experimentalObjectRestSpread": false}},// Specify the environment, each environment has its own predefined global variables, can specify multiple environments at the same time, without contradiction
"env": {
// The effect is the same as that of ecmaVersion
"es6": true."browser": true."node": true."commonjs": false."mocha": true."jquery": true.// If you want to use an environment from a plugin, be sure to specify the plugin name in the plugins array
// Format: plug-in name/environment name (plug-in name without prefix)
"react/node": true
},
// The specified environment provides us with preset global variables
// We can specify globals for our own global variables
// Set each variable equal to true to allow the variable to be overwritten, or false not to allow the variable to be overwritten
"globals": {
"globalVar1": true."globalVar2": false
},
//ESLint supports the use of third-party plugins
Before using the plugin, you must install it using NPM
// Globally installed ESLint can only use globally installed plug-ins
// Locally installed ESLint can use locally installed plug-ins as well as globally installed plug-ins
// Plugin differs from extend: Extend provides a set of presets for existing esLint rules
Plugins, on the other hand, provide custom rules in addition to the default, when you can't find one in esLint's rules
// You can borrow a plug-in to do this
"plugins": [
"eslint-plugin-airbnb".// The eslint-plugin- prefix can be omitted from the plugin name
"react"].// Specific rule configuration
//off or 0-- turns off the rule
// WARN or 1-- open rules, warning level (does not cause program exit)
//error or 2-- enable the rule, error level (when triggered, the program will exit)
"rules": {
"eqeqeq": "warn".// You can also define the severity of the rule using the corresponding number
"curly": 2.If a rule has additional options, you can specify them using array literals
// Options can be strings or objects
"quotes": ["error"."double"]."one-var": ["error", {
"var": "always"."let": "never"."const": "never"}].// To configure the custom rule provided by the plug-in, the format is: plug-in name without prefix/rule ID
"react/curly": "error"
},
//ESLint supports adding sharing Settings to configuration files
// You can add Settings objects to the configuration file, which will provide each rule to be executed
// If you want to add custom rules and make them accessible to the same information, this is useful and easy to configure
"settings": {
"sharedData": "Hello"
},
//Eslint checks configuration files:
//1. Look for.eslintrc.* and package.json in the same directory as the file to be tested
//2. Then look in the parent directory until you reach the root directory of the file system
//3. If root: true is found in the previous two steps, stop searching in the parent directory. Eslintrc
//4. If none of the preceding steps is found, go back to the default user-defined configuration in the user home directory ~/.eslintrc
"root": true.// The extends property value can be a string or an array of strings
// Each configuration item in the array inherits its previous configuration
// Optional configuration items are as follows
//1. string eslint: recommended, a configuration item that enables a set of core rules that report common problems, i.e. rules checked in (rules page)
//2. A shareable configuration package that outputs configuration objects, such as eslint-config-standard
// Shareable config is a simple NPM package that exports configuration objects. The package name starts with eslint-config- and is installed before use
// The extends property value can omit the package name prefix eslint-config-
//3. A plugin package that outputs configuration rules, such as eslint-plugin-react
Some plug-ins can also output one or more named configurations
// The extends property value is plugin: package name/configuration name
//4. A relative or absolute path to the configuration file
String ESlint: all, which enables all core rules in the currently installed ESLint
// This configuration is not recommended for production as it changes with the ESLint version. Use at your own risk
"extends": [
"eslint:recommended"."standard"."plugin:react/recommended"."./node_modules/coding-standard/.eslintrc-es6"."eslint:all"]}Copy the code