This article is only technical verification, recording, communication, not for anyone. Please forgive me if I have offended you. In this paper, starting from https://vsnail.cn/static/doc/blog/eslintPrettier.html
The idea of using ESLint and Prettier in projects has been around for a long time. But the love affair between ESLint and Prettier, plus the way framework (Vue, React) was written (JSX, Template), made development painful, confusing and confusing. So esint is enabled every time, then disabled, then enabled, then disabled, and so on and so on. Some time ago looking at front-end engineering related materials, I found that in fact, engineering code format specification is one of the important links. While esLint and Prettier spend the weekend working on efficient and standardized development,
On the road to code specification, our ultimate goals are:
All the developers on the team use one set of code to standardize the rules, and we don’t have to spend much effort on formatting for formatting’s sake. We want an automated tool that can help us check if our code is standard, and if it is not, it can automatically help us format it according to the given specification.
Eslint and Prettier in general, prettier is used to format code. Eslint implements the setting of code specification rules and warnings such as WARN and error on code. So our big goal should be esLint, and then integrate Prettier.
ESLint
ESLint is an open source JavaScript code checking tool created by Nicholas C. Zakas in June 2013. Code review is a static analysis that is often used to find problematic patterns or code and is not dependent on specific coding styles. Most programming languages have code checks, and compilers typically have built-in checks.
All rules in ESLint are designed to be pluggable. ESLint’s default rules are no different from other plugins, and the rules themselves and tests can rely on the same schema. So being configurable and plug-in is the biggest thing about ESLint, and that’s why we love using it.
How to configure
ESLint can be configured in two ways:
- use
JavaScript
Annotations embed configuration information directly into a code source file - Configuration file style
Of the two methods, Configuration file is the most common. Use JavaScript, JSON, or YAML files to specify configuration information for the entire directory (handling your home directory) and its subdirectories. ESLint finds and automatically reads them, and you can specify an arbitrary configuration file at command line runtime.
ESLint supports configuration files in several formats:
JavaScript
– use.eslintrc.js
It then outputs a configuration object.YAML
– use.eslintrc.yaml
或.eslintrc.yml
To define the configuration structure.JSON
– use.eslintrc.json
To define the structure of the configuration,ESLint
的JSON
File to allowJavaScript
Style notes.- (deprecated) – use
.eslintrc
, you can makeJSON
It can also be YAML. package.json
– inpackage.json
Create aeslintConfig
Property, where you define your configuration.
If there are multiple configuration files in the same directory, ESLint will only use one. The priorities are as follows:
.eslintrc.js
.eslintrc.yaml
.eslintrc.yml
.eslintrc.json
.eslintrc
package.json
Because js can be very convenient to write logic, and its priority is relatively high, so it is recommended to use JS files as configuration files.
What does this configuration mean
Configurability is one of the features of ESLint. That means we have to know what each configuration item means in order to play with ESLint. So let’s take a look at what common configuration items mean.
Parser
ESLint uses Espree as its parser by default. You can specify a different parser in the configuration file.
The following parsers are compatible with ESLint:
- Esprima
- Babel-eslint – A wrapper around the Babel parser to enable it to work with
ESLint
Compatible. - Typescript-eslint-parser (Experimental) – A parser that converts typescript to ESTree compatible formats so that it can be parsed in
ESLint
Is used in. The purpose of this is to passESLint
To parse TypeScript files (though not necessarily all of them)ESLint
Rules). Note that when using a custom parser, in order to makeESLint
In dealing with theECMAScript 5
Properties work properly when configuredparserOptions
Still a must. The parser is passed inparserOptions
, but they are not necessarily used to switch on or off features.
parserOptions
This property is often used to set some configurations of the grammar parser. The options available are:
-
ecmaVersion
: setECMAScript
Version.
The default is 3,5 (the default), and 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
Source code type
Set to “script” (default) or “module” (if your code is an ECMAScript module).
-
ecmaFeatures
This is an object that represents additional language features you want to use:
-
3.1 globalReturn – Allows return statements in a global scope
-
3.2 impliedStrict – Enable global Strict mode (if ecmaVersion is 5 or higher)
-
3.3 JSX – Enable JSX
-
3.4 experimentalObjectRestSpread – enable experimental object rest/spread properties support. (Important: This is an experimental feature and may change significantly in the future. It is recommended that you write rules that do not rely on this feature, unless you are willing to bear the maintenance costs when it changes.
Setting parser options helps ESLint determine what is a parsing error. All language options default to false
Environments
This configuration property defines a set of predefined global variables. Available environments include:
browser
– Global variables in the browser environment.node
–Node.js
Sum of global variablesNode.js
Scope.commonjs
–CommonJS
Sum of global variablesCommonJS
Scope (forBrowserify/WebPack
Packaged code that runs only in the browser).shared-node-browser
–Node.js
和Browser
Universal global variables.es6
– Enabled exceptmodules
All butECMAScript 6
Feature (This option is set automaticallyecmaVersion
The parser option is 6).worker
–Web Workers
Global variables.amd
–require()
和define()
Defined asamd
Same global variables.mocha
– Add allMocha
Test global variables.jasmine
– Add allJasmine
Versions 1.3 and 2.0 test global variables.jest
–Jest
Global variables.phantomjs
–PhantomJS
Global variables.protractor
–Protractor
Global variables.qunit
–QUnit
Global variables.jquery
–jQuery
Global variables.prototypejs
–Prototype.js
Global variables.shelljs
–ShellJS
Global variables.meteor
–Meteor
Global variables.mongo
–MongoDB
Global variables.applescript
–AppleScript
Global variables.nashorn
–Java 8 Nashorn
Global variables.serviceworker
–Service Worker
Global variables.atomtest
–Atom
Test global variables.embertest
–Ember
Test global variables.webextensions
–WebExtensions
Global variables.greasemonkey
–GreaseMonkey
Global variables. These environments are not mutually exclusive, so you can define more than one at once.
Globals
When we use global variables provided by third parties (e.g. jQuery,AMap, etc.), ESLint will not recognize them and will always report errors. This is where the configuration comes in. Use globals to indicate which global variables you want to use. Setting a variable to true will allow it to be overwritten, or false will not.
Plugins
ESLint supports the use of third-party plugins. Before you can use the plug-in, you must install it using the package management tool. When configuring plug-ins in a configuration file, you can use the plugins keyword to store a list of plug-in names. The eslint-plugin- prefix can be omitted from the plugin name.
Rules
ESLint comes with a lot of rules. You can use comments or configuration files to modify the rules to be used in your project. To change a rule setting, you must set the rule ID to either OFF, WARN, or ERROR.
Inheriting configuration files
The basic configuration properties to use are covered above. But as we’ve seen before, ESLint is not only configurable, it’s pluggable as a plugin. So how does the plug-in work? Plug-ins simply enhance some functionality and provide an interface. In ESLint, plugins are typically inherited to provide specific functionality.
extends
A configuration file can inherit enabled rules from the underlying configuration.
The extends property value can be:
(1) A string specified in the configuration
(2) String arrays: Each configuration inherits its previous configuration
ESLint extends configurations recursively, so a base configuration can also have an extends property.
Extends introduces shared configuration packages and plug-ins
- Shared Configuration package
The shareable configuration is an NPM package that outputs a configuration object.
The extends property value can omit the prefix eslint-config- of the package name.
- The plug-in
A plug-in is an NPM package that typically outputs rules. Some plug-ins can also output one or more named configurations.
The plugins attribute value can omit the package name prefix eslint-plugin-.
The extends property value can be composed of:
(1), plugin: (2), package name (omit prefix, e.g. React) (3), / (4), configuration name (e.g. Recommended)
Prettier
Prettier is a code formatting tool. To be able to format our code according to our rules.
Why do we use it instead of another code formatting tool? Prettier has the following advantages:
- Can be configured to change
- Support for multiple languages
- Integrate most editors
- Concise configuration items
ESLint
+ Prettier
All the developers on the team use one set of code to standardize the rules, and we don’t have to spend much effort on formatting for formatting’s sake. We want an automated tool that can help us check if our code is standard, and if it is not, it can automatically help us format it according to the given specification. —— our ultimate goal
From what we’ve seen above, the ultimate goal seems to be to use the two together. So how do you integrate them?
Take VUE project as an example:
Step 1: Download the package
For the most basic, we must download esLint, Prettier.
Second, in order to integrate it, we need to have written “shared configuration packages” and plug-ins. So we need to download eslint-plugin-prettier,eslint-config-prettier.
Third, we need to stand on the shoulders of giants to see the world. That is, we need some mature specifications in the industry to regulate our code. So we can use code specification plug-ins provided by large teams. The famous one is Airbnb. Here we choose Airbnb-base. So we need to download eslint-config-Airbnb-base.
Finally, to make perfect use of some of our new ES6 features. We need to set the “lexical parser” to babel-esLint. So we also need to download babel-esLint.
By the way, we are a VUE project, so there must be a plugin for vUE configuration, so we need to download eslint-plugin-vue
In summary, we need to download the following packages
npm install esint prettier eslint-plugin-prettier eslint-config-prettier eslint-config-airbnb-base babel-eslint eslint-plugin-vue
Copy the code
Step 2 Create the configuration file
This step is somewhat mechanical if you have carefully read the previous ESLint configuration items. So I’ll just copy the configuration file from the project and comment on it.
In the root directory of the project, create a.eslintrc.js file with the following contents:
module.exports = {
env: {
browser: true.jquery: true.// Due to the use of jquery in the project... In fact, there is no need to introduce jquery. Please remove this configuration when you have the opportunity to remove jquery.
},
parserOptions: {
parser: 'babel-eslint'.// The lexical parser uses babel-esLint to better adapt to the new ES6 API
ecmaVersion: 6.// Enable ES6 syntax support; The default is 3,5 (the default), and 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: 'module'.// Set to "script" (default) or "module" (if your code is an ECMAScript module).
},
extends: [
'airbnb-base'.'eslint:recommended'.'plugin:vue/essential'.'plugin:prettier/recommended',].plugins: ['vue'.'prettier'].rules: {
'prettier/prettier': 'error'.'generator-star-spacing': 'off'.'import/no-named-as-default': 'off'.'import/no-named-as-default-member': 'off'.'no-unused-vars': [
'error',
{ vars: 'all'.args: 'none'.ignoreRestSiblings: false},].// No error will be reported if no parameter is used. Because I feel that writing up the available parameters is conducive to future maintenance.}};Copy the code
The development tools
ESlint and Prettier were already configured as of the previous step. But to automate formatting, we need to do some integration.
The goal of automatic formatting can be achieved in development tools, but also in WebPack. I actually prefer to implement automatic formatting in development tools because it seems faster.
In development tools, we want to be able to format the code automatically after the changes are saved. How to achieve this goal? Let’s take VScode as an example
-
- Open the
VScode
Configuration file of
- Open the
-
- Add the following configuration.
."prettier.eslintIntegration": true."eslint.autoFixOnSave": true."editor.formatOnSave": true.// Configure the file types that ESLint checks
"eslint.validate": ["javascript"."javascriptreact"."vue"."html"]."eslint.options": {
"configFile": "./`.eslintrc`.js"},...Copy the code
webpack
In addition to working on development tools, you can also work on packaged compilation tools to achieve the goal of automatic formatting. Let’s take webpack as an example:
Since vUE projects usually use official scaffolding, SO I will directly above the picture, not BB. (Actually it is too late, I have to go to work tomorrow, my wife has urged me again)
Afterword.
There’s a lot more you can do with ESLint in terms of code specification.
For example, we could add a script to check if the code is canonical.
We can also do an automatic check before git commit to prevent the team from submitting non-standard code. You can borrow some of the code Review effort, and you can focus code review on the logic of the code itself.
All right, good night