Demand is briefly

Why use esLint and Prettier together? Because ESLint only checks code writing, it ensures a uniform code writing style. 3, Prettier prettier makes sure code is neat in formatting, such as how it wraps lines, indents, and so on. So a qualified project esLint +prettier configuration is essential.

Why use TypeScript goes without saying. Are there any front-end projects that don’t use TS?

So the objectives are:

  • Eslint +prettier+typescript perfect support

  • Project Lint will run bug-free (important!) no matter on whose computer or in what environment.

Make sure that all members of the team can perform lint operations without bugs as long as they use vscode, including the typescript version they use. (This is especially important, as configuring ESLint is not difficult, but it’s the biggest headache to run into problems where my computer works and yours doesn’t.)

precondition

Install vscode and install the eslint plugin.

Why do you need the ESLint plugin? Because we need ESLint to check our code in real time and alert us to code that doesn’t conform to the specification. This functionality is provided by plug-ins. The plugin will start a background task when our project starts, read the esLint configuration local to the project, and perform subsequent Lint operations. No Need to install Prettier? It can be installed. It’s just not necessary. If you only have TS and JS files in your project and no other types of files, you don’t have to install Prettier. Because our solution would incorporate Prettier’s plug-in into esLint’s configuration file, ESLint would naturally call where Prettier’s ability is needed, without Prettier creating a service in the background.

Configuration eslint

Install dependencies

pnpm install eslint eslint-plugin-import eslint-config-airbnb-base -D
Copy the code

Eslint-plugin-import is a peer-dependencies file that needs to be imported.

Airbnb’s ESLint rules are the mainstream set of ESLint rules. It provides different packages for different technology stacks. The reason why we don’t use eslint-config-airbnb or eslint-config-airbnb-typescript package is because it contains the React-related configuration, which I don’t need, so I just need to introduce eslint-config-airbnb-base.

Adding a Configuration File

.eslintrc.js

module.exports = {
  extends: ['eslint-config-airbnb-base']
}
Copy the code

.eslintignore

/node_modules
/dist
Copy the code

Added lint shortcut commands

Add script after package.json file.

{
   "scripts": {
    "lint": "eslint 'src/**/*.{js,ts}' --fix"
  }
}
Copy the code

File suffixes are added as needed.

Configuration typescript

Vscode supports ts by default without introducing plug-ins or typescript dependencies. But I recommend introducing typescript dependencies. The reason is that there are quite a few differences in capabilities between each minor version of TS. There is no way for everyone on the team to have the same version of vscode. Versions of natural TS are not guaranteed to be consistent. Let’s go down to 👇 to see the scheme.

Install dependencies

pnpm install typescript @typescript-eslint/eslint-plugin @typescript-eslint/parser -D
Copy the code

Tslint is no longer maintained, so use @typescript-eslint/eslint-plugin instead. The effect, of course, is to make a series of ESLint rules for TS.

The @typescript-esLint /parser function is to parse TS statements. Eslint itself does not support TS syntax.

Increase the configuration

Add the. Vscode folder in the root directory of the project, and add the settings.json file below.

{
  "typescript.tsdk": "./node_modules/typescript/lib",
}
Copy the code

Add this configuration line. The meaning is that the ts SDK path used by vscode in the project is the ts we rely on, not the built-in ts version of vscode! Make sure the team is using the same TS SDK.

New tsconfig. Json

{
  "compilerOptions": {
    "target": "es2015",
    "module": "ES2015",
    "lib": ["esnext", "dom"],
    "strict": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "moduleResolution": "node",
    "forceConsistentCasingInFileNames": true,
    "noUnusedLocals": true,
    "esModuleInterop": true,
    "noFallthroughCasesInSwitch": true,
    "noUnusedParameters": true,
    "noEmit": true,
    "skipLibCheck": true,
    "rootDir": "src",
    "baseUrl": ".",
    "allowJs": true
  },
  "include": ["src"],
  "exclude": ["node_modules"],
}
Copy the code

Here are only the configuration items I recommend, most of which you can check the official website for other configuration items.

Modified. Eslintrc. Js

module.exports = {
  extends: ['eslint-config-airbnb-base', 'plugin:@typescript-eslint/recommended'],
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint'],
  rules: {
    'import/extensions': 'off',
    'no-use-before-define': 'off',
    '@typescript-eslint/no-use-before-define': ['error', { ignoreTypeReferences: true }],
    'import/prefer-default-export': 'off',
  },
  settings: {
    'import/resolver': {
      node: {
        extensions: ['.js', '.ts'],
        moduleDirectory: ['node_modules', './src'],
      },
    },
  },
  parserOptions: {
    project: './tsconfig.json',
  },
}
Copy the code

You can see that there are many more rules all of a sudden. Talk briefly about why and what the problem was solved.

  • You don’t want to write file suffixes while importing other modules, so turn off the import/ Extensions rule.
  • Interface and Type in typescript do not suffer from variable promotion, so two lines of rules have been added to ensure that ESLint does not complain when interface or type is used before declaration.
  • If there is only one export item in a single file, ESLint will tell you to export it as export default. If your project is going to be an NPM library or A UI library, I urge you not to use Export Default, so turn this rule off. As to the reason for their own search, pit is bigger to say.

Ts – support node

If our project is a tool library, we’ll probably need TS-Node to help us easily execute typescript scripts. Here added, the person who needs it can be taken by himself.

Install dependencies

pnpm install ts-node -D
Copy the code

Ts-node executes scripts

Add the following configuration items to script in package.json

{
   "scripts": {
    "test": "npx ts-node --project ./tsconfig.json ./src/filename.ts",
  },
}
Copy the code

Because Node does not support esModule (certain conditions are required), add the following configuration items in the tsconfig.json file

{
   "ts-node": {
    "transpileOnly": true,
    "compilerOptions": {
      "module": "commonjs"
    }
  }
}
Copy the code

Configuration is prettier

Install dependencies

pnpm install prettier eslint-plugin-prettier eslint-config-prettier -D
Copy the code

Prettier is introduced as peer-dependencies. Eslint-config-prettier Shuts off ESLint rules prettier than Prettier EsLint-config-prettier Shuts off ESLint rules where prettier does not exist . Eslint-plugin-prettier tells ESLint how to format a document as Prettier does.

Increase the configuration

The. Prettierrc file was added

{
  "semi": false,
  "tabWidth": 2,
  "singleQuote": true,
  "trailingComma": "es5",
  "printWidth": 140
}
Copy the code

Can configure not much, look at yourself.

Modified. Eslintrc. Js

module.exports = {
  extends: ['eslint-config-airbnb-base', 'plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended'],
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint'],
  rules: {
    'import/extensions': 'off',
    'no-use-before-define': 'off',
    '@typescript-eslint/no-use-before-define': ['error', { ignoreTypeReferences: true }],
    'no-prototype-builtins': 'off',
    'import/prefer-default-export': 'off',
  },
  settings: {
    'import/resolver': {
      node: {
        extensions: ['.js', '.ts'],
        moduleDirectory: ['node_modules', './src'],
      },
    },
  },
  parserOptions: {
    project: './tsconfig.json',
  },
}
Copy the code

Ensure that the plugin: prettier/it in the final.

Modify settings.json (Important)

Automatically perform lint operations when the project needs to be saved. If it’s a non-JS or TS file, prettier is usually needed to format the code style. So we still need to install the prettier plug-in and format it for saving using Prettier. Hence the following configuration items.

{
  "typescript.tsdk": "./node_modules/typescript/lib",
  "editor.codeActionsOnSave": {
    "source.fixAll": true
  },
  "[javascript]": {
    "editor.defaultFormatter": "dbaeumer.vscode-eslint"
  },
  "[typescript]": {
    "editor.defaultFormatter": "dbaeumer.vscode-eslint"
  },
  "editor.defaultFormatter": "esbenp.prettier-vscode"
}
Copy the code

Specifying the default formatting tool is important. Even if your ESLint and other configuration items are correct, your default formatting tool is incorrect if the code flickers when you save.

The last

Front-end environment configuration is a headache. Just what ESLint is configured for is also complicated. It’s not just a matter of adding a few packages and then extends and turning off a few rules. You need to know how vscode is configured, specify formatting tools, how to not fight prettier, support ts, react, etc. Once and for all, I hope you don’t step on the pit.

And last but not least, not least. That’s the version problem. Eslint will also cry if the plugin and ESLint versions don’t match! I’ve already stepped in this hole. My current dependent version is the latest and no problem version, I put it below.

{"@typescript-eslint/eslint-plugin": "^5.3.0", "@typescript-eslint/parser": "^5.3.0", "eslint": ", "" ^ 8.1.0 eslint - config - reality - base", "^ 14.2.1", "eslint - config - prettier" : "^ 8.3.0", "eslint - plugin - import" : "^ 2.25.3 eslint", "- the plugin - prettier" : "^ 4.0.0", "prettier" : "^ against 2.4.1"}Copy the code