JavaScript code style

Posted by senyo on Mon, 06 Jan 2020 02:35:07 +0100

JavaScript code style

1. specification

In order to agree on your code style, some relatively standard code style specifications have been born in the community:

2. ESLint

ESLint only provides tools and rules, how to configure these rules depends on the user. This is illustrated by the Airbnb configuration.

2.1. installation

Reference resources: https://www.npmjs.com/package/eslint-config-airbnb

$ npm info "eslint-config-airbnb@latest" peerDependencies
{ eslint: '^4.19.1',
  'eslint-plugin-import': '^2.12.0',
  'eslint-plugin-jsx-a11y': '^6.0.3',
  'eslint-plugin-react': '^7.9.1' }


$ npx -v
6.1.0

$ npx install-peerdeps --dev eslint-config-airbnb
+ eslint-config-airbnb@17.0.0
+ eslint-plugin-jsx-a11y@6.1.1
+ eslint-plugin-react@7.10.0
+ eslint-plugin-import@2.13.0
+ eslint@4.19.1
SUCCESS eslint-config-airbnb and its peerDeps were installed successfully.

2.2. configuration

# Create package.json
$ npm init -y

$ eslint --init
? How would you like to configure ESLint?
  Answer questions about your style
❯ Use a popular style guide
  Inspect your JavaScript file(s)

? Which style guide do you want to follow?
  Google
❯ Airbnb
  Standard

? Do you use React? No
? What format do you want your config file to be in? JSON

+ eslint-plugin-import@2.13.0
+ eslint-config-airbnb-base@13.0.0

Finally, generate the. eslint.json file:

{
    "extends": "airbnb-base"
}

2.3. use

2.3.1. On the command line

$ ./node_modules/.bin/eslint -v
v4.19.1

$ ./node_modules/.bin/eslint ./blog/

/Users/forwardNow/develop/work/study/blog/2018/08/test.js
  35:1  warning  Unexpected console statement  no-console1 problem (0 errors, 1 warning)

2.3.2. Configure npm script

"scripts": {
  "eslint": "./node_modules/.bin/eslint ./src/"
},

2.3.3. In vscode

Search and install the eslint plug-in

To configure User Settings:

"editor.detectIndentation": false,
"editor.tabSize": 2,

"eslint.autoFixOnSave": true,

Topics: Javascript npm React JSON