preface

Code specifications are important, and the most important thing a code specification does is to reduce the likelihood that the code will make mistakes.

There are many articles on code specifications, but unfortunately none of them cover all of them, so let this one do what the others didn’t.

The content of this article applies to both Web development and applets (applets developer tools).

Will learn

  • Beginner: Use of ESLint and ESLint configuration — making code conform to javascript code specifications
  • Formatting code — Formatting code so that it looks pretty
  • Using the vscode extension to save automatic specification code – save work
  • [Advanced] Use Husky to ensure that the submitted code complies with the code specification — the last barrier
  • Advanced Configuration of TypeScript code specifications

Look at the

I don’t need to talk about the importance of code specification, but what should we do to achieve the goal of code specification?

This article will go through every step of the way to standardize your code. Refer to the steps “Will Learn” above for details of the process.

To operate

ESLint configuration – Specification code

ESlint’s purpose is to ensure code consistency and avoid errors.

Install eslint.

npm install eslint --save-dev
Copy the code

Initialize the configuration file

The initial configuration file is executed in the project root directory, and an. Eslintrc file is generated in the root directory.

eslint --init
Copy the code

Execute check and repair commands

The check code specification command, the –ext option is used to specify a comma-separated list of extension names, such as.js,.ts, with the last parameter indicating the path of the file to be checked.

eslint --ext .ts,.js .
Copy the code

Review and fix code specification commands.

eslint --fix --ext .ts,.js .
Copy the code

For more options, see the ESLint command line

For ease of use, we can add two commands directly to package.json

"scripts": {
  "lint": "eslint --ext .ts,.js ."."lint:fix": "eslint --fix --ext .ts,.js ."
},
Copy the code

If we want to customize the rules of some code specification, we can modify the.eslintrc file.

Configuration of the sample

This is the eslintrc reference configuration, where extends and plugins are understood as rule sets. The difference is that extends specifies a common set of rules, while plugins are complementary rule sets.

// Small program engineering.eslintrc
module.exports = {
  // Enable default core rules
  extends: ['@tencent/eslint-config-tencent'].// Specify the inherited configuration name, which overwrites the previous one
  plugins: ['prettier'].// Plugin package, you can omit the package name prefix "eslint-plugin-"
  parserOptions: { // Specify the supported JavaScript language options
    ecmaVersion: 2018.sourceType: 'module'.ecmaFeatures: {
      impliedStrict: true,}},env: { An environment defines a set of predefined global variables
    browser: true.node: true.es6: true,},// Add your own rules
  rules: { // Override the rules in the base configuration
    // Disable the debugger in non-development mode
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'warn'.// Allows calls to specified uppercase functions without the new operator
    'new-cap': ['error', { capIsNewExceptions: ['App'.'Page'.'Component']}],'@typescript-eslint/no-require-imports': 'off',},// Configure global functions in applets to avoid errors
  globals: {
    require: true.Page: true.wx: true.App: true.getApp: true.getCurrentPages: true.Component: true.getRegExp: true,}};Copy the code

Similarly, in the VUE project, you can refer to the following configuration.

// Vue project.eslintrc
module.exports = {
  extends: ['@tencent/eslint-config-tencent'.'plugin:vue/recommended'].plugins: ['eslint-plugin-vue'.'prettier'].parserOptions: {
    parser: '@babel/eslint-parser'.// parseroptions. parser is a parser that parses 
    ecmaVersion: 2018.sourceType: 'module'.ecmaFeatures: {
      impliedStrict: true,}},globals: {
    app: true,}};Copy the code

Prettier Configuration – Beautifies code

Eslint makes code conform to the code specification, but the format fix isn’t complete. To fix the format, there’s another library called Prettier.

Prettier can format JavaScript files, You can also format TypeScript · Flow · JSX · JSON·CSS · SCSS · Less·HTML · Vue · Angular·GraphQL · Markdown · YAML files.

Install prettier.

npm install prettier --save-dev
Copy the code

Execute formatting command

— Write: local modification.

npx prettier --write index.css
Copy the code

Likewise, if a custom formatting is needed, the. Prettierrc file in the root directory can be used to configure some custom formatting rules.

Using eslint – plugin – prettier

Instead of directly using the prettier library, we use eslint-plugin-prettier, where Prettier is a plug-in for ESLint. Just as in the example code in the previous section, configure the plugins option to the.eslintrc file.

Eslint-plugin-prettier As an ESLint plug-in that includes the prettier library, there is no need to run the prettier command alone.

VSCode plug-ins and configuration – simplifies specification work

Eslint and eslint-plugin-prettier format code by running esLint –fix — ext.ts,.js. Command, every time modify the code, but also to run a command, is really more troublesome.

We can simplify this step with a plug-in for VSCode. The end result is that we just write the code normally, and as soon as we save it, it’s automatically formatted.

Install ESLint and Vetur plugins

Here we need to use the ESLint plugin, and for vue projects we also need to use the Vetur plugin.

Prettier plugin not necessary because we already use eslint-plugin-prettier

VSCode can search for installed plug-ins directly.

Wechat developer tools now also supports the installation of VSCode plug-ins, just need to open the editor extension panel in Settings – extension Settings – to find the corresponding plug-in to install.

Configure save automatic formatting

After installing the plugin, there will only be alarms for code that does not conform to the specification, but it will not be automatically fixed. In order to do this, we need to make some Settings for VSCode.

Add the. Vscode directory under the root directory, create setting.json file under the directory, and add the following Settings. To avoid conflicts between turning off vetur and esLint configurations, turn off some vetur formatting options.

//setting.json
{
    // The following program is used to format the Vue project, other projects can follow the principle of everything.
    // Set formatting when saving. Only used to format CSS/LESS programs
    "editor.formatOnSave": true."javascript.format.enable": false."typescript.format.enable": false.// Close vetur js/ts/ HTML formatter. HTML is formatted with eslint-plugin-vue.
    // js/ts uses eslint to prevent prettier in vetur from formatting in conflict with ESLint
    "vetur.format.defaultFormatter.html": "none"."vetur.format.defaultFormatter.js": "none"."vetur.format.defaultFormatter.ts": "none".// Enable esLint to automatically fix JS /ts
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true}},Copy the code

Eslint and formatting issues will be fixed automatically if you click Save.

Share VSCode plug-ins and configurations with other developers

setting.json

By uploading.vscode/setting.json to git repository, we can share the vscode Settings that save automatic formatting with the project developer, but we still need to install the plug-in manually.

extensions.json

It is also possible, we can add extensions. Json file under.vscode to configure the recommended plug-in. Or, even easier, just right-click the plugin and click Add to Workspace Suggestion to generate a file like the one below.

//extensions.json
{
    "recommendations": [
        "dbaeumer.vscode-eslint"."octref.vetur"]}Copy the code

Other project developers can view and install recommended plug-ins simply by typing @recommended in the extended search box.

Configure HusKY – To prevent submission of non-standard code

With the previous three safeguards, our code is pretty well regulated, but there is still the possibility of submitting unregulated code to git without installing the eslint plugin for vscode or running eslint commands.

To secure the last line of defense before committing your code, husky (tick marks before Git submission) will be used to inspect your code and forbid it from being submitted if it fails to be checked. Lint-staged checks will only be performed on buffer files to speed up the inspection.

Install the husky

NPM install [email protected] - save - devCopy the code

Install the lint – staged

npm install lint-staged --save-dev
Copy the code

Configuration package. Json

"husky": {
	"hooks": {
		"pre-commit": "lint-staged"}},"lint-staged": {
  "*.{js,ts,vue}": [
  	"eslint"]}Copy the code

At this point, if the code has errors, the commit will fail.

Note: Fixed SourceTree skipping husky

– Can’t find NPX in path Can’t find NPX in path Can’t find NPX in path In order to resolve this error, husky normal check, we need to add the path of NPX.

Refer to this documentation for the husky local command

Create a ~/. Huskyrc file in the system root directory and add the directory where NPX is located, for example:

Which NPX/Users/Username/NVM/versions/node/v12.18.0 / bin/NPX vim ~ /. Huskyrc / / write to export PATH = / Users/Username /. NVM/versions/node/v12.18.0 / bin: $PATHCopy the code

Other issues prevented Husky from working

If the.git/hooks file is not correctly generated, delete the hooks and reinstall husky.

Make ESlint support TypeScript

The installation

To support TypeScript checking, we need to add TS-related parsers and plug-ins

npm install --save-dev typescript @typescript-eslint/parser
npm install --save-dev @typescript-eslint/eslint-plugin
Copy the code

configuration

And modify the eslintrc. Js

module.exports = {
  // ...
  parser: '@typescript-eslint/parser'.plugins: ['@typescript-eslint'.'eslint-plugin-vue'.'prettier'].// ...
};

Copy the code

After configuration, VSCode autofix and ESLint will also apply to TS files.

Note: Resolve conflicts with vUE resolution

The “Use the latest VUe-eslint-parser “error is reported after the configuration is executed because it conflicts with the vUE parser.

We move the TS parser directly into parserOptions

- "parser": "@typescript-eslint/parser",
+ "parser": "vue-eslint-parser"."parserOptions": {+"parser": "@typescript-eslint/parser"."ecmaVersion": 2020."sourceType": "module"
  }
Copy the code

conclusion

At this point, all the configuration is complete. For complete configuration files, please refer to the following two files: eslintrc.js. Just use it!! 😄

Applets complete configuration

module.exports = {
  // Enable default core rules
  extends: ['@tencent/eslint-config-tencent'].// Specify the inherited configuration name
  plugins: ['@typescript-eslint'.'prettier'].// Plugin package, you can omit the package name prefix "eslint-plugin-"
  parser: '@typescript-eslint/parser'.// Specify the parser
  parserOptions: { // Specify the supported JavaScript language options
    ecmaVersion: 2018.sourceType: 'module'.ecmaFeatures: {
      impliedStrict: true,}},env: { An environment defines a set of predefined global variables
    browser: true.node: true.es6: true.jest: true,},// Add your own rules
  rules: { // Override the rules in the base configuration
    // Disable the debugger in non-development mode
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'warn'.// Allows calls to specified uppercase functions without the new operator
    'new-cap': ['error', { capIsNewExceptions: ['App'.'Page'.'Component']}],'@typescript-eslint/no-require-imports': 'off',},// Configure global functions in applets to avoid errors
  globals: {
    require: true.Page: true.wx: true.App: true.getApp: true.getCurrentPages: true.Component: true.getRegExp: true,}};Copy the code

Vue is fully configured

module.exports = {
  extends: ['@tencent/eslint-config-tencent'.'plugin:vue/recommended']."parser": "vue-eslint-parser".plugins: ['@typescript-eslint'.'eslint-plugin-vue'.'prettier'].parserOptions: {
    parser: ['@typescript-eslint/parser'.'@babel/eslint-parser'].// parseroptions. parser is a parser that parses 
    ecmaVersion: 2018.sourceType: 'module'.ecmaFeatures: {
      impliedStrict: true,}},globals: {
    app: true,}};Copy the code

reference

ESLint Documentation in Chinese

Prettier document

Eslint plugin – prettier document

Husky document

Eslint and prettier NPM packages and vscode add-ons for eslint and prettier

In 2022, won’t you take advantage of vscode’s shared configuration and teamwork?

Past oliver

Say goodbye to Bad Code

【 Front-end Exploration 】 Say goodbye to bad code! Encapsulate network requests in the chain of responsibility pattern

【 Front-end Exploration 】 Say goodbye to bad code # 2! Encapsulate sharing components with policy patterns

The code of life

[Thinking on three years of front-end development] How to read requirements effectively?

Front end step pit must see guide

[Front-end exploration] Best practices for image loading optimization

[Front-end exploration] Exploration of mobile terminal H5 to generate screenshot posters

[Front-end Exploration] H5 to obtain user positioning? This one is enough

【 Front-end exploration 】 The exploration of wechat small program jump — Why does open label exist?

VConsole fancy usage