Reference:

How to gracefully use ESLint and Prettier in a Typescript project

My electron tutorial series

Configuration for using ESLint and Prettier in a Vue + Typescript project

Using ESLint and Prettier in a TypeScript Project

ESLint + TS + Prettier complete configuration ESLint + TS + Prettier complete configuration ESLint + TS + Prettier complete configuration ESLint + TS + Prettier

The relationship between ESLint core dependencies, editor plug-ins, and ESLintWebpackPlugin in Webpack

If you’re using another editor or packaging tool, you can look up the integration plugins/dependencies for ESLint

ESLint Core dependencies

Dependent downloads: NPM install eslint -d When we write a project, the intuitive feeling is that ESLint will do the following:

  1. Check for grammar errors
  2. Output the error to the console
  3. Added an error modal to the development environment page
  4. The production environment found an error and stopped the package
  5. Format files when saving (with prettier)

In practice, however, these operations are not done by ESLint alone. The core step that ESLint does is to check for syntax errors.

  1. The file is parsed by a defined parser to generate an AST tree
  2. Categorize errors with default/custom rules (error, Warning)

This site gives you an intuitive understanding of the various parsers and AST tree astExplorer.net/

This feature is mainly provided by ESLint core dependencies. That is, after downloading and configuring an ESLint dependency from a project via NPM install ESLint -d, You have the ability to find errors based on your configuration, but you need additional plug-in support for how to display those errors.

VSCode plug-in – ESLint

Download: search for ESLint in the VSCode App Store

Functions: Editor support is required to flag code in red when it does not conform to esLint configuration specifications, or to enable a number of ESLint-related configurations, such as esLint saving the auto-call code fix (–fix) function

For example, after downloading the ESlint plugin, you need to configure the types of files that the editor will detect in the preferences Settings. If you do not configure them, they will not take effect

// ESLint plug-in's basic configuration settings.json
{
	"eslint.validate": [
		"javascript"."typescript"."javascriptreact".// JSX 
		"typescriptreact"		// TSX
	]
// Save the automatic call to eslint --fix [file], which is provided by VSCode's ESLint plugin
	"editor.codeActionOnSave": {
		"source.fixAll.eslint": true
	}
Copy the code

Webpack plug-in ESLintWebpackPlugin

Download: NPM install eslint-webpack-plugin — save-dev

Functions: WebPack plug-in, if the project encountered syntax errors detected by ESLint during packaging, the development environment: console to print error information, you can embed full-screen modal in the page to display error information; In production: The packaging run can be stopped. You can change how the ESLintWebpackPlugin is handled by changing its configuration. ESLintWebpackPlugin

If you use Webpack to package a project and start a local development environment with webpack-dev-server, then the console print in the development environment is controlled by Webpack. Webpack does not know what ESLint errors are and must cross a bridge. The eslint-webpack-plugin establishes the connection between them. The same is true in production.

How do I configure ESLint, Typescript, and Prettier in a project

The basic idea

The three dependencies of the ESLint+ editor + packaging tool described above actually meet all our requirements for formatting code

If you want to use Prettier to format code in a project, there are two ways for Prettier to be used. One way Prettier provides rules for ESLint and uses ESLint’s fix function for Prettier to format code. The second way you can use Prettier to provide rules for ESLint is to format code using the same Prettier rules using the Prettier plugin in the editor

In our project, “Prettier” is used to provide rules. The advantage of “Prettier” is that the formatting configuration structure of the project is clearer and there is no need to download redundant editor plug-ins

The formatting process is as follows:

  1. ESLint reads configuration files.eslintrc.jsTo check code for errors or warnings that do not conform to the specification
  2. Configuration editor (VSCode), turn on the auto-fix function for saving files (auto-fix), only some specific errors can be automatically fixed, such as semicolons, colons, etc

Whether you use Vue, typescript, or React, the steps for formatting your code are exactly the same. The only difference is how ESLint defines the errors in the first step. That is, ESLint’s configuration is different for different technology stacks. This is why there are so many plugins for ESLint, right

Let’s take a look at ESLint’s basic configuration, which is a configuration with no additional plugins added:

// .eslintrc.js
module.exports = {
	// The environment in which the Enviroment project is running. This can be configured to provide you with global variables such as the Browser environment allowing you to use the Windows API
	env: {
		browser: true.node: true
	},
	parser: 'espree'.// EsLint's default parser
	extends: ['eslint:recommended'].// Enable some of esLint's core rules, but you can also add other default rules based on project requirements
	rules: { // A user-defined rule that overrides the default rule configured in the extends
		semi: ["error"."always"].quotes: ["error"."double"]},plugins: [] // Third-party plug-ins that can provide additional rules, default configurations (config), global environment variables, etc
}
Copy the code

The ultimate goal of an entire ESLint configuration is to make a rule and then check if the code complies with that rule. For some rules, if the error level is error, you can fix the file by using ESLint –fix. This configuration file can be divided into two parts:

  • env,extends,rules,pluginsFields are all for rules
  • parserField specifies the parser used to generate the AST tree. ESLint’s default parser isespreeProject files using typescript require third-party dependencies to change the parser

Add typescript detection

Related,

  • @typescript-eslint/parser EsLint’s parser for parsing typescript, thereby checking and standardizing typescript code
  • @typescript-eslint/eslint-plugin This is an ESLint plugin that contains various defined specifications for detecting typescript code

Configuration after adding typescript rule detection

module.exports = {
	env: {
            browser: true.node: true
	},
	parser: '@typescript-eslint/parser'.// Use the typescript parser
	extends: [
            'eslint:recommended'.'plugin:@typescript-eslint/recommended'].// Add typescript's core rules
        
        plugins: ['@typescript-eslint'] // Add typescript plugins so you can use typescript rules
	rules: {
		semi: ["error"."always"].quotes: ["error"."double"].'@typescript-eslint/no-explicit-any': 0  // Typescript rules}},Copy the code

The Prettier rule is added

Related,

  • Eslint-config-prettier EsLint-config-prettier esLint-config-prettier esLint-config-prettier esLint-config-prettier esLint-config-prettier esLint-config-prettier esLint-config-prettier esLint-config-prettier esLint-config-prettier
  • Eslint-plugin-prettier Disable esLint and prettier have conflicting rules

After adding the Prettier rule, note that the later configuration items in the extends array overwrite the previous ones. “Prettier” must be placed last, so that “fix” prevails

module.exports = {
	env: {
            browser: true.node: true
	},
	parser: '@typescript-eslint/parser'.extends: [
            'eslint:recommended'.'plugin:@typescript-eslint/recommended'.'prettier'].// Adds the core rule for Prettier
        plugins: ['@typescript-eslint'.'prettier'].// Add the prettier plug-in to provide rules for prettier
	rules: {
		// semi: ["error", "always"],
     // Quotes: ["error", "double"], // Rules override extends rules. Remove rules that affect formatting
		'@typescript-eslint/no-explicit-any': 'error'.'prettier/prettier': 'error'./ / configuration error level for prettier error, in order to make exlint - fix can fix the errors
		'arrow-body-style': 'off'.'prefer-arrow-callback': 'off'}},Copy the code

Eslint plugin – prettier provides a quick configuration, the prettier configuration and the configuration of the above effects:

module.exports = {
	env: {
            browser: true.node: true
	},
	parser: '@typescript-eslint/parser'.extends: [
            'eslint:recommended'.'plugin:@typescript-eslint/recommended'.'plugin:prettier/recommended'].// Adds the core rule for Prettier
        plugins: ['@typescript-eslint'].rules: {
            // semi: ["error", "always"],
            // quotes: ["error", "double"],
            '@typescript-eslint/no-explicit-any': 'error',}}Copy the code

Arrow-body-style and prefer-arrow-callback are the two rules prettier recommends closing, which in some cases cause ESLint autofix bugs

If you use arrow-body-style or prefer-arrow-callback together with the prettier/prettier rule from this plugin, you can in some cases end up with invalid code due to a bug in ESLint’s autofix – see issue #65 .

— from the official document for eslint-plugin-prettier

Prettier reads the configuration of.tierrc. js in the root directory of an Prettier project for its rules, and these rules override the default rules in the extends rule. If the configuration doesn’t take effect on an Prettier project, the Prettier shut down the editor and open it again

module.exports = {
    semi: false.trailingComma: 'all'.endOfLine: 'auto'.tabWidth: 2.singleQuote: true
    / /... For details, see official configuration
}
Copy the code

This completes the Typescript ESLint + + Prettier the formatting of the configuration, if your project using the Vue or React or other technology stack, you just need to change on ESLint rules, recommended configuration according to your own project selected in line with their own here depend on the package

Dependencies required by the project:

  • eslint
  • prettier
  • typescript
  • @typescript-eslint/parser
  • @typescript-eslint/eslint-plugin
  • eslint-config-prettier
  • eslint-plugin-prettier

Plugin for editor (we chose to use ESLint for autoFix, no prettier plug-in for prettier)

  • eslint
  • typescript

Complete configuration:

// .eslintrc.js
module.exports = {
	env: {
            browser: true.node: true
	},
	parser: '@typescript-eslint/parser'.extends: [
            'eslint:recommended'.'plugin:@typescript-eslint/recommended'.'plugin:prettier/recommended'].// Adds the core rule for Prettier
        plugins: ['@typescript-eslint'].rules: {
            // semi: ["error", "always"],
            // quotes: ["error", "double"],
            '@typescript-eslint/no-explicit-any': 'error',}}// setting.json
{
    "eslint.validate": [
        "javascript"."typescript"."javascriptreact"."typescriptreact"].// File saving automatically calls eslint --fix
    "editor.codeActionOnSave": {
        "source.fixAll.eslint": true}}// .prettierrc.js
module.exports = {
    semi: false.trailingComma: 'all'.endOfLine: 'auto'.tabWidth: 2.singleQuote: true
    / /... For details, see official configuration
}
Copy the code

Eslint feels like a lot of dependencies every time you configure it, but the overall flow is simple and there aren’t many configuration files

Hopefully, this article helped you understand how ESLint works with other plugins to complete code formatting

Git commit verification will be added after the plan, and a document will be written after the test