Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 0ed59fa

Browse files
committed
更新 TypeScript 与 ESLint
1 parent 37828d2 commit 0ed59fa

File tree

2 files changed

+50
-3
lines changed

2 files changed

+50
-3
lines changed

assets/typescript-eslint.png

320 Bytes
Loading

ecosystem/eslint.md

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,61 @@
66

77
## 为什么需要 ESLint
88

9-
TypeScript 已经可以对代码进行静态检查了,那么为什么还需要 ESLint 呢?
9+
TypeScript 除了是一个编译 ts 文件的工具以外,还可以[作为一个静态代码检查工具使用]()
10+
11+
TypeScript 会对文件进行语法解析,如果遇到一些语法错误,或使用了未定义的变量,则会报错。
12+
13+
ESLint 也会对文件进行语法解析,它可以对一些代码风格进行约束,发现未定义的变量,但是对于错误的属性或方法引用,却无能为力。
14+
15+
我们对同样一段代码分别运行 `tsc``eslint`,会得到如下报错信息:
16+
17+
```ts
18+
let myName = 'Tom';
19+
20+
comsole.log(`My name is ${myName}`);
21+
console.log(`My name is ${myNane}`);
22+
console.log(`My name is ${myName.toStrng()}`);
23+
console.log(`My name is ${ myName }`)
24+
25+
// tsc 报错信息:
26+
//
27+
// index.ts(3,1): error TS2552: Cannot find name 'comsole'. Did you mean 'Console'?
28+
// index.ts(4,27): error TS2552: Cannot find name 'myNane'. Did you mean 'myName'?
29+
// index.ts(5,34): error TS2551: Property 'toStrng' does not exist on type 'string'. Did you mean 'toString'?
30+
//
31+
//
32+
// eslint 报错信息:
33+
//
34+
// index.ts
35+
// 3:1 error 'comsole' is not defined no-undef
36+
// 4:27 error 'myNane' is not defined no-undef
37+
// 6:25 error Unexpected space(s) after '${' template-curly-spacing
38+
// 6:35 error Unexpected space(s) before '}' template-curly-spacing
39+
// 6:38 error Missing semicolon semi
40+
//
41+
// ✖ 5 problems (5 errors, 0 warnings)
42+
// 3 errors, 0 warnings potentially fixable with the `--fix` option.
43+
```
44+
45+
| 存在的问题 | `tsc` 是否报错 | `eslint` 是否报错 |
46+
| --------- | ------------- | ---------------- |
47+
| `console` 被勿写成了 `comsole` | ✔️ | ✔️ |
48+
| `myName` 被勿写成了 `myNane` | ✔️ | ✔️ |
49+
| `toString` 被勿写成了 `toStrng` | ✔️ ||
50+
| 模版字符串中 `${}` 内前后多出了两个空格 || ✔️ |
51+
| 少了一个分号 || ✔️ |
52+
53+
上例中,由于 `eslint` 无法识别 `myName` 存在哪些方法,所以对于拼写错误的 `toString` 没有检查出来。后面两个错误是代码风格,不影响编译,故 `tsc` 没有检查出来。而未定义的变量两者都能检查出来。
54+
55+
值得注意的是,`tsc` 不仅检查出来了代码问题,还非常智能的给出了修改建议。
1056

11-
其实 ESLint
57+
下面 TypeScirpt 作为一个静态代码检查工具,与 ESLint 的关系图:
1258

1359
![TypeScript 和 ESLint 的关系](../assets/typescript-eslint.png)
1460

61+
上图中,静态代码检查包括了很多种,其中 TypeScirpt 与 ESLint 有重叠的部分,也有各自独立的部分,虽然发现代码错误比统一的代码风格更重要,但是当一个项目越来越庞大,开发人员也越来越多的时候,代码风格的约束还是必不可少的。
1562

16-
下面我们来一步一步给我们的 TypeScript 项目添加 ESLint 检查。
63+
下面我们就来一步一步给我们的 TypeScript 项目添加 ESLint 检查。
1764

1865
## 安装
1966

0 commit comments

Comments
 (0)