Please read the getting Started guide to using Eslint

With the basic Eslint usage guide behind us, we can move on to our project and take a step-by-step look at how to add Eslint configuration to an old project as an example. Since the framework used in the company is VUE, let’s use the VUE project as an example to add configuration.

A, addEslintBasic configuration

  • NPM install Eslint -d

  • Initialize the configuration file NPX eslint –init

    1. There are different options to choose from here, and eventually a configuration file will be generated. You can also create it manually, so you can just generate it once, change it to your own configuration file, and then copy it for later projects.
      • To check syntax only
      • To check syntax and find problems
      • To check syntax, find problems, and enforce code style
      • JavaScript modules (import/export)
      • CommonJS (require/exports)
      • None of these
      • React
      • Vue.js
      • None of these
      • Does your project use TypeScript?
      • Browser
      • Node
      • JavaScript
      • YAML
      • JSON
      • Would you like to install them now with npm?
  • Following the steps above, we generate the following base configuration file, which we analyzed in the GETTING Started guide to using Eslint, so we just need to look at what is generated by default?

    module.exports = {
        "env": {
            "browser": true,
            "es2021": true,
            "node": true
        },
        "extends": [
            "eslint:recommended",
            "plugin:vue/essential"
        ],
        "parserOptions": {
            "ecmaVersion": "latest",
            "sourceType": "module"
        },
        "plugins": [
            "vue"
        ],
        "rules": {
        }
    }
    Copy the code

    There is a slight difference between the extends extends plugin and plugin for VUE projects: VUE /essential and plugin for plugin. As we mentioned earlier, Eslint only supports js files by default. In order to handle.vue files, We need to use this plug-in, which is installed after we select Vue during cli configuration file generation. You can find this plug-in in package.json. As we mentioned earlier, Extends and plugins can be omitted if they are named eslint-plugin- or eslint-config-, so the full name of the plugin is eslint-plugin-vue. Also extends includes built-in esLint: Recomended rules and plugin:vue/essential. The former are rules we know esLint has built in, but you can remove them if you don’t like them, because in later practice it turns out that the built-in commands aren’t really best practices either. We call it the official conservative plan.

    ESLint initially found it too difficult because it was too superstitious about authority. For example, The JavaScript style of Airbnb has been highly praised on GitHub. In fact, I also recognize this kind of coding style. But each team can customize according to the actual situation of their own different things, the scene is different, the thing is different, the team’s code level also have differences, so we can’t literally copying, for many things, keep a reference way, still need to give attention to both team’s advice to specify acceptance scheme, After all, if a specification is used by many people, it needs to be accepted by all.

    Eslint :recommended After reading most open source projects you will find that most of them do not use the official built-in rule. Most authors will choose the Airbnb team’s specification with the idea of borrowing and learning from it. I think teams can learn from this idea and do not use the built-in rule. Switched to airbnb’s team specifications, so let’s tweak it a little bit.

Using airbnb specifications

NPM install eslint-config-airbnb -d NPM install eslint-config-airbnb -d

  • We need to remove it from the official default configuration esLint :recommended, replace it with Airbnb, and then we retest the file

    Not surprisingly, at this point we found an error indicating that we were missing eslint-plugin-jsx-a11y. This is clearly the React JSX file, which we don’t need in the Vue project. NPM install eslint-config-airbnb-base -d eslint-config-airbnb-base -d eslint-config-airbnb-base

  • Airbnb is inherited from Airbnb-base, which supports the React project by default. We don’t need it, so we just need to use the Base package. Of course, the base package also relies on the ESlint-plugin-import package, so we also need to download this package. The purpose of this package is to detect packages that have problems with paths and invalid exports when importing files.

  • To sum up, if we want to use Airbnb in VUE project, we only need to download these two packages. NPM insta eslint-config-airbnb-base eslint-plugin-import -d

  • If you are using vue-CLI to generate projects, you will have this package built in and you will also have validation commands built in scripts. If you are using VUe-CLI, you will not have validation commands built in, so we will manually configure these two commands:

    "lint": "eslint --ext .js,.vue src",
    "lint:fix": "eslint --fix --ext .js,.vue src"
    Copy the code
  • At this point, NPM Run Lint will check and, if anything, your project will have a lot of problems.

  • Airbnb-base rule reference

Custom rules or extended rules

Through the above steps we have a set of other open source rules, but not necessarily very applicable, we need to extend it or don’t fit the team rules we need to be closed, how to achieve this, we just need to add our own rules in the rules, or modify the rules of the people, because of the weight of rules is the highest, The configuration here is the highest priority. We need to negotiate with the team to complete this step.

The following problems arise here that we need to deal with

  • Team specifications need to be agreed upon by a number of people

  • If it’s not cost-effective to repeat every project like this,

    • We can pull out a public file for maintenance, just put it in the specified directory and then extens to the specified path, of course it would be troublesome to copy it every time
    • We can also order oneeslint-config-xxxPublish specifications suitable for your team tonpmjsMarket or publish to the company internallyNPM platform, which can be downloaded every time at the project NPM, further improving the simplicity of configuration, but still requiring manual implementation
    • Better methods we can inherit to the companycliIn tools, it is relatively convenient to generate such configuration files through scaffolding with one click, and each update only needs to be updated from scaffolding, which can be synchronized, which may be convenient for the team
  • Pure Eslint specification making is just one step, verbal rules are not binding, we need tool enforcement to implement the specification we define, which includes a relatively large set of tools, we’ll talk about this later.

Auto repair

Format of each encounter a few problems, such as space, quotes such small problems, if every time to manually adjust really takes energy, we can use the IDE to automatically save, but everyone’s editor is different, so this is also need to consider problem, now we are using is Vscode team, although it is the same editor, We can’t expect other people to have the same configuration as us but we need to follow the same specifications for a particular project, so we can configure.vscode in the project and create settings.json in the file, where the configuration weight takes precedence over the global, Here we configure some configuration about the editor to regulate the use of the editor, here is a simple configuration in save is automatic repair:

{"eslint.validate": [" HTML ", "vue", "javascript", "JSX "], // Need to check the language" emmet.syntaxprofiles ": {"vue-html": "html", "vue": "html" }, "editor.wordWrapColumn": 220, "editor.codeActionsOnSave": { "source.fixAll.eslint": True // Enable saving commands that autofix esLint can fix}}Copy the code

This is a relatively basic configuration, you can configure a lot of things in it, including themes, text, various rules, etc., which take precedence over the configuration file rules in the root directory.

Once configured, we have saved what auto-fix Eslint can fix (not everything can be fixed here)

Plug-in enhancements

We know that Eslint has a lot of plugins, and a lot of people are confused and don’t know what to do with the various packages. We can look at the plugins list, and there are various plugins.

Eslint-plugin-babel: A plug-in that works with babel-esLint. Babel-eslint does a good job of applying ESLint to Babel, but it can’t change the built-in rules to support experimental features. Eslint-plugin-babel reimplements the rule in question so that some error messages are not misreported

Eslint-plugin-import: This plugin wants to support validation of the ES2015+ (ES6+) import/export syntax and prevent misspelled file paths or incorrect import names

Eslint-plugin-jsx-a11y: This dependency package focuses on checking the accessibility of JSX elements.

Eslint-import-resolver-webpack: Webpack configurations can be used to assist ESLint resolution, most usefully with aliases, to avoid unresolved errors

Eslint-import-resolver-typescript: similar to eslint-import-resolver-webpack, eslint-import-resolver-typescript resolves alias problems

Eslint-plugin-react: react-specific validation rule plug-in.

Eslint-plugin-jest: Jest-specific esLint rule verification plug-in.

Eslint-plugin-prettier: This plug-in helps ESLint work smoothly with Prettier, parsing prettier as part of ESLint, and editing the final output. So when Prettier formats code, she still follows our Eslint rules. The plugin works better if you disable all Eslint rules related to code formatting. So you can disable formatting rules by using eslint-config-prettier (an error is inevitable if prettier does not conform to a valid ESLint rule on how code is formatted)

@typescript-eslint/eslint-plugin: Plugins for typescript to assist ESLint.

Eslint-plugin-promise: The promise specification is written as a check plug-in, with some validation rules.

More configuration & Configuration meaning

Of course, all of the above custom generated configurations are not comprehensive enough. After we understand the functions of different plug-ins, we will look at other configuration options and the use of different configurations.

  • Env environment configuration, we usually need to use Node, brower, Es6, etc., it can coexist can contain multiple environments.

    • Es6 uses all ECMAScript6 features, excluding modules, which are automatically added when ecmaVersion is configured
    • browerWill add all browser variables, such aswindowsIf not added, an error will be reportedundefind
    • Node does the same thing with the globle global variable wait
    • For more configurations, see the official documents
  • Extends: Specifies the configuration of an extension, a combination of rules, which overwrites the previous one when there are more than one.

  • Plugins configure the Lint plugin we need to use.

  • Parser uses the Espree parser by default. If we use some new feature syntax or something like bable, we need to use bable- esLint. I think the project needs to be included by default

  • ParserOptions When we change the default parser from Espree to babel-esLint, we need to specify parseOptions, which is mandatory.

    • EcmaVersion: The default value is 5 and can be set to 3, 5, 6, 7, 8, 9, 10 to specify which ECMAScript version of the syntax to use. You can also set JS standards based on year, such as 2015(ECMA 6)
    • SourceType: If your code is written by an ECMAScript module, this field is configured tomodule, or forscript(Default), basically we need to configure tomodule
    • EcmaFeatures: This object indicates additional language features you want to use
  • Rules Configures custom rules. A high priority overrides the extends configuration

  • Settings The data defined by this field can be shared across all plug-ins. This allows each rule execution to access the data defined within it

Supporting optimization process and engineering integration

  • Husky: Git workflow hook configuration

  • Lint-staged hook functions can be customized to perform some Lint-validation-strong project specification at certain stages in certain Git hooks.

  • Prettier: Prettier: a tool for unifying code style Eslint can only standardize your syntax and a few small syntax conventions, not the overall style of code, so you need it, but there are a lot of packages that can be confusing, so here’s what to do:

    • Prettier Original basic version, which defines some basic rules. For the supported rules, see Configuring addresses

    • Prettier-eslint: Input code, prettier, eslint –fix Output formatted code Only strings are supported.

    • Prettier-eslint-cli: As the name implies, the CLI can be used to perform prettier-eslint

      Usually, Eslint works with prettier, but prettier configuration conflicts with Eslint, where the plugin eslint-config-prettier overwrites Eslint. Disable all rules that conflict with PrettTier so that you can use eslint-plugin-prettier to configure your own code style rule without thinking about ESLint’s rules, which implements our configuration but makes some ESLint configurations meaningless. Prettier-eslint so the tool prettier-esLint was born, but it only supported code strings prettier-eslint-CLI

  • Following this we will use Eslint + Prettier + Husky + Lint-staged to complete the entire configuration of a project.

Vue project base template

With that said, here’s a basic template that doesn’t include Prettier, and we’ll integrate other tools later.

Module. exports = {"root": true, // tell the editor not to look for config files "env": {// config environment "browser": true, "es2021": true, "node": true }, "extends": [// use the airbnb-base rule and eslint-plugin-vue rule to match. Vue file "airbnb-base", "plugin:vue/essential"], "parser": {"ecmaVersion": "latest", // version "sourceType": {"ecmaVersion": "latest", // version "sourceType": "The module", / / module | script "ecmaFeatures" : {} / / want to use the new language features}, "plugins" : [" vue "], / / eslint - plugin - vue "rules" : {} // Customize rules and configure override rules}Copy the code

Write in the last

The configuration of the Eslint specification for the VUE project is basically complete. More specifications need to be defined with your team. Here is only the content of the Eslint part, we still need to complete the rest in the future to complete the integration of other ancillary functions for the project.

Related articles
  • Basic Reference: Getting Started with Eslint
  • Project Usage Guide: Use Eslint in old VUE projects