Everyone may have their own code style and format, but a project will run much more smoothly if everyone in the project follows the same style. Not everyone will agree on every formatting rule, and many of them will take some getting used to, but it is important to follow a common programming style throughout the project so that everyone can read and understand the code easily.

Updated on 2018.07.27 First published in Xia Wei’s blog: xiaweiss.com

This article has many pictures, if you want to see the article with pictures, please click here to read the original article

introduce

There are three related concepts about code formatting that can be confusing

  1. Code format: manually customized, or following a common specification such as JavaScript Standard Style, Airbnb JavaScript Style, Google JavaScript Style, etc.)
  2. Code checking: To indicate non-conforming code (ESLint, TSLint, stylelint, etc.) according to a specified code format
  3. Code format: The act of modifying code (ESLint, Prettier, etc.) that does not conform to a specified code format

The formatting tool supports CLI mode. You can configure commands in package.json (for other parameters in CLI mode, refer to official documents).

"scripts": {
  "standard": "standard --fix",
  "prettier": "prettier --write '*.js'",
  "eslint": "eslint --fix '*.js'"
},
Copy the code

You can format your JavaScript code in one of the following ways, from simple to strict

  1. Using EditorConfig, add the configuration file.editorconfigYou can set the basic formatting of the section, and then use the editor’s default formatting
  2. Use Prettier, no code inspection, formatting. You can also add configuration files.prettierrcCustom format
  3. Use the Standard JavaScript Standard Style and install it directlynpm install standard --save-devNo configuration files are required. Then use the Standard plugin for formatting (you can check without installing ESlint code)
  4. Using ESLint, execute the command linenpx eslint --initYou can initialize it and then select the configuration rules. After that, the configuration file is automatically generated and dependencies are installed. And you can customize the rules. Then use plugin formatting (either the ESLint plugin, or both Pretter + ESLint)

An example.editorConfig file:

root = true

[*]                             # [] is the regular expression that matches the file
charset = utf-8                 # Text format
end_of_line = lf                # Configure the end symbol
insert_final_newline = true     Empty line at end of file
indent_style = space            # Indent with Spaces
indent_size = 2                 # Indent length
trim_trailing_whitespace = true Remove extra space at the end of the line
Copy the code

For code review of CSS, NPM install stylelint –save-dev Installation code format NPM install stylelint-config-standard –save-dev Vue The file also requires a preprocessor NPM install @mapbox/stylelint-processor-arbitrary-tags –save-dev

Add the configuration file.stylelintrc

{
  "defaultSeverity": "warning"."processors": ["@mapbox/stylelint-processor-arbitrary-tags"]."extends": "stylelint-config-standard"."rules": {}}Copy the code

Which can write custom rules in the rules, the custom rules of highest priority to generate its own custom rules, can visit the web site https://maximgatilin.github.io/stylelint-config/

An editor plug-in for stylelint, formatted using stylefmt or Prettier

The following is the configuration of the various editor plug-ins

Webstorm configuration

Enable EditorConfig

To install the plugin EditorConfig, go to Settings Editor -> Code Style and check Enable EditorConfig support to create the. EditorConfig file and restart the Editor

The editor defaults to formatting

Menu bar Code -> Reformat Code shortcut Alt + Cmd + L

Formatting the Prettier plug-in

Webstorm uses a built-in Prettier plugin that does not need to be installed. Phpstorm, for example, can be installed in Plugins in the setup center

2. Install the NPM dependency package for Prettier globally or as a project

npm install prettier --save-dev
Copy the code

3. Format the file Alt + Shift + Cmd + P using Prettier

Settings saved automatically when formatting: hand Tools in the configuration Settings – > File, which can be Can according to the official tutorial at https://prettier.io/docs/en/webstorm.html

Go to Settings, search for Prettier, and copy the path in the Prettier package

Clear the search bar, open Tools -> File Watchers in Settings, click ➕ plus in the lower left corner on the right, and select < Custom > to create a custom template

And then you can see (notice click on the triangle arrow to expand all the options)

Click ok at the bottom right corner to finish the configuration (please create another one when using Vue, and select Vue Template as the file type).

$ProjectFileDir$/node_modules/.bin/prettier
--write $FilePathRelativeToProjectRoot$
$FilePathRelativeToProjectRoot$
$ProjectFileDir$
Copy the code

Windows must contain CMD suffix, Programs

$ProjectFileDir$/node_modules/.bin/prettier.cmd
Copy the code

Restart the editor and then format the code automatically whenever Ctrl + S saves

ESLint formatting

1. Install the NPM dependency packages for ESLint globally or within a project

npm install eslint --save-dev
Copy the code

2. Open the editor configuration, as shown below, and find the ESLint configuration item. The path will be detected automatically, just check Enable (if there is no path, restart the editor or manually specify the path of the ESLint NPM package).

3. Restart the editor. 4

You are advised to set Ctrl + Alt + F

Set automatic formatting when saving: The same as Prettier, create a File Watcher

$ProjectFileDir$/node_modules/.bin/eslint
--fix $FilePathRelativeToProjectRoot$
$FilePathRelativeToProjectRoot$
$ProjectFileDir$
Copy the code

Windows must contain CMD suffix, Programs

$ProjectFileDir$/node_modules/.bin/prettier.cmd
Copy the code

Restart the editor and then format the code automatically whenever Ctrl + S saves

(Create another file if using Vue. Select Vue Template as the file type.)

Standard Standard formatting

Install NPM dependencies. Note that they must be installed into development dependencies

npm install standard --save-dev
Copy the code

Set the JS code style to Standard (Webstorm defaults to Google style). The location of the source points set here is shown in the picture below. For Editor -> Code Style -> JavaScript -> Warping and Braces -> Set from… -> Predefined Style -> JavaScript Standard Style

Then use the editor’s default formatting function, Alt + Cmd + L

Enable code checking (optional, format errors will not be displayed if not set) : Open the ESlint configuration screen above, check Enable, and select the ESlint package as the standard NPM path

Prettier + ESLint used alongside Prettier + ESLint

When Prettier and ESLint were configured as before, WebStorm automatically formatted Pretter before ESLint formatted code

VSCode configuration

Enable EditorConfig

Install the plugin EditorConfig for VS Code and restart the editor to create the.EditorConfig file

The editor defaults to formatting

The shortcut keys Shift + Alt + For Cmd + Shift + P bring up the command panel, enter format, and select Format Document

Formatting the Prettier plug-in

Prettier-code Formatter still uses Shift + Alt + F

Set the automatic Formatting switch: Install Formatting Toggle, the Formatting button will appear in the bottom right corner, click on the Formatting function, it will automatically modify the user Settings file, configure “editor.formatOnPaste”: true, “editor.formatOnSave”: true,

If the switch is not set, automatic formatting at save time needs to be set: add “editor.formatOnSave”: true to the Settings in the editor

ESlint formatting

Double-click on the red wavy line and a small yellow light bulb will appear. Click on the bulb and then on Fix to complete formatting

Or enter Cmd +Shift+P (win: Ctrl+Shift+P) to bring up the command panel and enter fix

You can also add a custom configuration to set automatic formatting when saving:

"eslint.autoFixOnSave": true.Copy the code

Standard Standard formatting

Install NPM dependencies. It is recommended to install them in development dependencies

npm install standard --save-dev
Copy the code

Install the plugin JavaScript Standard Style

Enter Cmd +Shift+P (win: Ctrl+Shift+P) to bring up the command panel. Enter the command fix to select Fix All auto-Fixable problems

You are advised to add a custom configuration:

"standard.usePackageJson": true, // based on the project's package.json Settings"standard.autoFixOnSave": true, // Automatic formatting when savingCopy the code

Prettier + standard Prettier + standard

Prettier and standard are configured, and

"editor.formatOnSave": true."standard.autoFixOnSave": true.Copy the code

When the file is saved, Prettier is formatted before Standard

Prettier + ESLint used alongside Prettier + ESLint

Configure the Prettier and standard as before, and set

"editor.formatOnSave": true."eslint.autoFixOnSave": true.Copy the code

Or configure Prettier only and set it to

"editor.formatOnSave": true."prettier.eslintIntegration": false// Use the prettier-eslint functionCopy the code

“Eslint. autoFixOnSave”: true,

Don’t install the ESLint plugin if you don’t need format checking prompts

The Atom configuration

The editor does not integrate formatting plug-ins by default

Enable EditorConfig

Install the editorConfig plug-in and restart the editor to create the.EditorConfig file

Formatting the Prettier plug-in

Install the plug-in prettier-atom, restart the editor and use Crtl + Alt + F formatting

Set automatic formatting switch: Under the Format on Save option in plugin Settings, check the Show in Status Bar editor at the bottom and the automatic formatting on Save switch will appear

ESLint formatting

Install the liner-ESLint plugin, restart the editor, click on the offending section, and then click fix to format it

To set automatic formatting on save: in linter-esLint plugin configuration, check this option

Standard Standard formatting

Install NPM dependencies. It is recommended to install them in development dependencies

npm install standard --save-dev
Copy the code

Use Ctrl + Alt + F to format code

Enable code checking (optional, no formatting error if not installed) : Install the plugin linter-js-standard

Prettier + ESLint used alongside Prettier + ESLint

Where Prettier + ESLint is configured and automatic formatting is enabled for save while Prettier + ESLint is configured

Or configure Prettier only, and check in the Prettier setting

You don’t need to install the ESLint standard-formatter plugin. If you don’t need the formatting check prompt, you don’t need to install the linter-js-standard plugin

Stylelint editor configuration

Install NPM dependencies. It is recommended to install them in development dependencies

npm install stylelint --save-dev
Copy the code

Set the configuration file. Stylelintrc see above

Installing the plug-in (similar to the above configuration, refer to the plug-in documentation for details)

Atom: plugin stylefmt or Vue – Stylefmt or pretter-atom(check Stylelint Integration in Settings) VScode: plugin stylefmt WebStorm: Settings -> Language and FrameWorks -> Stylesheets -> Stylelint -> Check Enable and set the stylelint NPM package path