catalogue
Why code checking is required §
Check the ts file of the whole project §
Integrate ESLint check in VSCode §
Fix formatting errors using Prettier §
Use the ESLint configuration of AlloyTeam §
Checking tsx files using ESLint §
Cannot find module '@typescript-eslint/parser'§
VSCode does not display the error message of ESLint §
Code check
In January 2019, TypeScirpt officially decided to fully adopt ESLint As a tool for code checking, and created a new project typescript-eslint , provides a parser for TypeScript files @typescript-eslint/parser And related configuration options @typescript-eslint/eslint-plugin Wait. The previous two lint solutions will be discarded:
- typescript-eslint-parser Maintenance stopped
- TSLint The migration tool will be provided, and the maintenance of TSLint will be stopped after the function of typescript eslint is complete enough (once we consider eslint feature complete w.r.t. TSLint, we will reduce TSLint and help users migrate to eslint) 1)
To sum up, the current and future code checking scheme for TypeScript is typescript-eslint.
What is code checking §
Code checking is mainly used to find code errors and unify code style.
In JavaScript projects, we generally use ESLint It greatly enriches the scope of application and collocation through the plug-in feature typescript-eslint After that, it can even be used to check TypeScript code.
Why code checking §
Some people think that JavaScript is very flexible, so it needs code checking. While TypeScript can check many problems at the compilation stage, why do you need code checking?
Because TypeScript focuses on type checking rather than code style. When more and more people on the team write the same logic, it may be very different for different people:
- Should the indentation be four spaces or two spaces?
- Should it be disabled var?
- Should the interface name be I start?
- Should it be mandatory === instead of ==?
TypeScript will not pay attention to these problems, but it will affect the efficiency, code understandability and maintainability of multi person collaborative development.
Let's take a specific example:
var myName = 'Tom'; console.log(`My name is ${myNane}`); console.log(`My name is ${myName.toStrng()}`);
Can you see any errors in the above code?
After compiling with tsc and checking with eslint respectively, the error message is as follows:
var myName = 'Tom'; // eslint error message: // Unexpected var, use let or const instead.eslint(no-var) console.log(`My name is ${myNane}`); // tsc error message: // Cannot find name 'myNane'. Did you mean 'myName'? // eslint error message: // 'myNane' is not defined.eslint(no-undef) console.log(`My name is ${myName.toStrng()}`); // tsc error message: // Property 'toStrng' does not exist on type 'string'. Did you mean 'toString'?
Existing problems | tsc Whether an error is reported | eslint Whether an error is reported |
---|---|---|
Should use let or const instead of var | ❌ | ✅ |
myName It was written by mistake myNane | ✅ | ✅ |
toString It was written by mistake toStrng | ✅️ | ❌ |
In the above example, we used var To define a variable, but there is a more advanced syntax in ES6 let and Const, you can pass eslint Check it out and prompt us that we should use it let or const instead of var.
For undefined variables myNane,tsc and eslint Can be checked out.
because eslint Unrecognized myName What methods exist, so for spelling errors toString Didn't check it out.
Thus, eslint Can find some tsc I don't care about errors and check out some potential problems, so code checking is still very important.
Using ESLint in TypeScript §
Install ESLint §
ESLint can be installed in the current project or in the global environment. Because code checking is an important part of the project, we usually install it in the current project. You can run the following script to install it:
npm install --save-dev eslint
Because ESLint is used by default Espree For syntax parsing, some syntax of TypeScript cannot be recognized, so we need to install it @typescript-eslint/parser , instead of the default parser, don't forget to install it at the same time typescript:
npm install --save-dev typescript @typescript-eslint/parser
Next, you need to install the corresponding plug-in @typescript-eslint/eslint-plugin As a supplement to the eslint default rules, it provides some additional rules applicable to ts syntax.
npm install --save-dev @typescript-eslint/eslint-plugin
create profile §
ESLint needs a configuration file to decide which rules to check. The name of the configuration file is usually . eslintrc.js or . eslintrc.json.
When running ESLint to check a file, it will first try to read the configuration file in the directory of the file, and then look up level by level to merge the found configuration as the configuration of the currently checked file.
We create one at the root of the project . eslintrc.js, as follows:
module.exports = { parser: '@typescript-eslint/parser', plugins: ['@typescript-eslint'], rules: { // var is prohibited 'no-var': "error", // interface is preferred over type '@typescript-eslint/consistent-type-definitions': [ "error", "interface" ] } }
In the above configuration, we have specified two rules, where no-var Is the native rule of ESLint, @ typescript ESLint / consistent type definitions yes @ typescript-eslint/eslint-plugin New rules.
The value of the rule is generally an array (in the above example) @ Typescript eslint / persistent type definitions), where the first item is off,warn or error The following items are other configurations of the rule.
If there is no other configuration, the value of the rule can be abbreviated as the first item in the array (in the above example) no-var).
The meanings of shutdown, warning and error reporting are as follows:
- Close: disable this rule
- Warning: error message will be output during code check, but exit code will not be affected
- Error reporting: when an error is found, not only the error message will be output, but also the exit code will be set to 1 (generally, if the exit code is not 0, it indicates an error in execution)
Check a ts file §
After creating the configuration file, let's create a ts file to see if we can check it with ESLint.
Create a new file index.ts, copy the following contents:
var myName = 'Tom'; type Foo = {};
Then execute the following command:
./node_modules/.bin/eslint index.ts
You will get the following error message:
/path/to/index.ts 1:1 error Unexpected var, use let or const instead no-var 3:6 error Use an `interface` instead of a `type` @typescript-eslint/consistent-type-definitions ✖ 2 problems (2 errors, 0 warnings) 2 errors and 0 warnings potentially fixable with the `--fix` option.
The above results show that the two rules just configured are effective: prohibit use var; preferred interface instead of type.
It should be noted that we use ./ node_modules/.bin/eslint, not global eslint Script, because code checking is an important part of the project, we usually install it in the current project.
However, it is inconvenient to execute such a long script every time. We can package.json Add a script To create an npm script to simplify this step:
{ "scripts": { "eslint": "eslint index.ts" } }
Just execute npm run eslint Just.
Check the ts file for the entire project §
Our project source files are generally placed in src Directory, so you need to package.json Medium eslint The script checks a directory instead. because eslint The default is not to check . ts Suffix file, so you need to add parameters -- ext .ts:
{ "scripts": { "eslint": "eslint src --ext .ts" } }
Execute at this time npm run eslint It will be checked src All in the directory . ts Suffix file.
Integrating ESLint checking in VSCode §
Integrating ESLint check in the editor can find errors in the development process, and even automatically repair errors when saving, which greatly increases the development efficiency.
To integrate ESLint check in VSCode, we need to install the ESLint plug-in, click the "extension" button, search ESLint, and then install it.
The ESLint plug-in in VSCode does not check by default . ts For suffix, you need to create a configuration file in "file = > Preferences = > Settings = > workspace" (you can also create a configuration file in the project root directory) . vscode/settings.json), add the following configuration:
{ "eslint.validate": [ "javascript", "javascriptreact", "typescript" ], "typescript.tsdk": "node_modules/typescript/lib" }
Then open another one . ts File, move the mouse to the red prompt, and you can see the error message:
We can also turn on the function of automatic repair when saving by configuring:
{ "eslint.autoFixOnSave": true, "eslint.validate": [ "javascript", "javascriptreact", { "language": "typescript", "autoFix": true }, ], "typescript.tsdk": "node_modules/typescript/lib" }
After saving the file, it can be automatically repaired as:
let myName = 'Tom'; interface Foo {}
Fix formatting errors using Prettier §
ESLint contains some code format checks, such as spaces, semicolons, etc. But there is a more advanced tool in the front-end community that can be used to format code, that is Prettier.
Prettier focuses on code formatting, reorganizes the code format through syntax analysis, and keeps everyone's code in the same style.
First you need to install Prettier:
npm install --save-dev prettier
Then create a prettier.config.js File, which contains prettier configuration items. Prettier has few configuration items. Here I recommend a configuration rule for your reference:
// prettier.config.js or .prettierrc.js module.exports = { // One line can be up to 100 characters printWidth: 100, // Indent with 4 spaces tabWidth: 4, // Use spaces instead of indents useTabs: false, // A semicolon is required at the end of the line semi: true, // single quotes singleQuote: true, // The key of the object is quoted only when necessary quoteProps: 'as-needed', // jsx does not use single quotes, but double quotes jsxSingleQuote: false, // Comma is not required at the end trailingComma: 'none', // Spaces are required at the beginning and end of braces bracketSpacing: true, // The inverse angle brackets of jsx tags need to wrap jsxBracketSameLine: false, // When the arrow function has only one parameter, parentheses are also required arrowParens: 'always', // The format range of each file is the whole content of the file rangeStart: 0, rangeEnd: Infinity, // You do not need to write @ prettier at the beginning of the file requirePragma: false, // There is no need to automatically insert @ prettier at the beginning of the file insertPragma: false, // Use default line break criteria proseWrap: 'preserve', // Determines whether html should be folded or not according to the display style htmlWhitespaceSensitivity: 'css', // Line breaks use lf endOfLine: 'lf' };
Next, install the Prettier plug-in in VSCode and modify it . vscode/settings.json:
{ "files.eol": " ", "editor.tabSize": 4, "editor.formatOnSave": true, "editor.defaultFormatter": "esbenp.prettier-vscode", "eslint.autoFixOnSave": true, "eslint.validate": [ "javascript", "javascriptreact", { "language": "typescript", "autoFix": true } ], "typescript.tsdk": "node_modules/typescript/lib" }
This enables automatic formatting and automatic repair of ESLint errors when saving files.
It should be noted that since ESLint can also check some code format problems, we will generally disable the rules related to code format in ESLint when used with Prettier, otherwise there will be conflicts.
Use the ESLint configuration of AlloyTeam §
ESLint native rules and @ typescript-eslint/eslint-plugin There are too many rules, and some native rules are not well supported in TypeScript and need to be disabled.
I recommend it here TypeScript version in AlloyTeam ESLint rule , it has provided us with a complete set of configuration rules and is fully compatible with Prettier (eslint config alloy does not contain rules of any code format, and the problem of code format is left to more professional Prettier).
Installation:
npm install --save-dev eslint typescript @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-config-alloy
Create in your project root directory . eslintrc.js and copy the following contents to the file:
module.exports = { extends: [ 'alloy', 'alloy/typescript', ], env: { // Your environment variables (including multiple predefined global variables) // Your environments (which contains several predefined global variables) // // browser: true, // node: true, // mocha: true, // jest: true, // jquery: true }, globals: { // Your global variable (set to false to indicate that it is not allowed to be reassigned) // Your global variables (setting to false means it's not allowed to be reassigned) // // myGlobal: false }, rules: { // Customize your rules // Customize your rules } };
For more usage, please refer to AlloyTeam ESLint rule
Checking tsx files using ESLint §
If you need to support checking tsx files at the same time, you need to make some adjustments to the above steps:
install eslint-plugin-react §
npm install --save-dev eslint-plugin-react
Add scripts.eslint in package.json . tsx suffix §
{ "scripts": { "eslint": "eslint src --ext .ts,.tsx" } }
New typescriptreact check in VSCode configuration §
{ "files.eol": "\n", "editor.tabSize": 4, "editor.formatOnSave": true, "editor.defaultFormatter": "esbenp.prettier-vscode", "eslint.autoFixOnSave": true, "eslint.validate": [ "javascript", "javascriptreact", { "language": "typescript", "autoFix": true }, { "language": "typescriptreact", "autoFix": true } ], "typescript.tsdk": "node_modules/typescript/lib" }
Use TypeScript React version in AlloyTeam ESLint rule §
TypeScript React version in AlloyTeam ESLint rule
Troubleshootings§
Cannot find module '@typescript-eslint/parser'§
You are running global eslint and need to run it instead ./ node_modules/.bin/eslint.
VSCode does not display the error message of ESLint §
- Check whether the configuration in "file = > Preferences = > Settings" is correct
- Check that the necessary npm packages are installed
- inspect . eslintrc.js Is there any configuration
- Check whether the file is in . eslintignore in
If none of the above steps works, you can configure it in file = > Preferences = > settings "eslint.trace.server": "messages", press Ctrl+Shift+U Open the output panel and select ESLint output to view the specific error.
Why are some variables defined (such as using enum The defined variable) is not used, but ESLint does not report an error? §
Because this kind of variable definition checking cannot be supported. Recommended in tsconfig.json Add the following configuration to make tsc The compilation process can check that unused variables are defined:
{ "compilerOptions": { "noUnusedLocals": true, "noUnusedParameters": true } }
After enabling noUnusedParameters, only the second parameter is used, but the first parameter must be passed in, which will report an error §
The first parameter can start with an underscore, refer to with --noUnusedParameters how can i skip uneeded parameters · Issue #9458 · microsoft/TypeScript · GitHub