Skip to content

Commit e61d6e1

Browse files
committed
常规更新
1 parent 9eb7436 commit e61d6e1

File tree

3 files changed

+581
-0
lines changed

3 files changed

+581
-0
lines changed

typescript/error.md

Lines changed: 280 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,280 @@
1+
### 备注
2+
该部分主要列举在typescript开发中遇到的各种问题与解决方案。
3+
4+
#### 1.顺序import问题
5+
<pre>
6+
Import sources within a group must be alphabetized.
7+
</pre>
8+
在tslint.json中添加如下内容即可,然后重启服务:
9+
```js
10+
"rules": {
11+
  "ordered-imports": false
12+
}
13+
```
14+
15+
#### 2.TypeScript coding guidelines say to not prefix interface with I
16+
在tslint.json里面添加如下内容:
17+
```js
18+
"rules": {
19+
"ordered-imports": false,
20+
"interface-name": [
21+
true,
22+
"never-prefix"
23+
]
24+
}
25+
```
26+
27+
#### 3.Cannot compile jsx if we provide `noImplicitAny` option
28+
```js
29+
"compilerOptions": {
30+
"baseUrl": ".",
31+
"outDir": "build/dist",
32+
"module": "esnext",
33+
"target": "es5",
34+
"lib": ["es6", "dom"],
35+
"sourceMap": true,
36+
"allowJs": true,
37+
"jsx": "react",
38+
"moduleResolution": "node",
39+
"forceConsistentCasingInFileNames": true,
40+
"noImplicitReturns": true,
41+
"noImplicitThis": true,
42+
"noImplicitAny": false,
43+
//这里设置为false
44+
"strictNullChecks": true,
45+
"suppressImplicitAnyIndexErrors": true,
46+
"noUnusedLocals": true,
47+
"allowSyntheticDefaultImports": true,
48+
"experimentalDecorators": true
49+
}
50+
```
51+
52+
#### 4.rootDir问题
53+
<pre>
54+
"error TS6059: File 'D:/workplace/nodeWP/testTS/index.tsx' is not under 'rootDir'
55+
</pre>
56+
我去掉了rootDir,然后使用exclude和include代替:
57+
```js
58+
{
59+
"compilerOptions": {
60+
"baseUrl": ".",
61+
"outDir": "build/dist",
62+
"module": "esnext",
63+
"target": "es5",
64+
"lib": ["es6", "dom"],
65+
"sourceMap": true,
66+
"allowJs": true,
67+
"jsx": "react",
68+
"moduleResolution": "node",
69+
"forceConsistentCasingInFileNames": true,
70+
"noImplicitReturns": true,
71+
"noImplicitThis": true,
72+
"noImplicitAny": false,
73+
"strictNullChecks": true,
74+
"suppressImplicitAnyIndexErrors": true,
75+
"noUnusedLocals": true,
76+
"allowSyntheticDefaultImports": true,
77+
"experimentalDecorators": true
78+
},
79+
// rootDir去掉了
80+
"include": ["./test/**/*.tsx", "./src/**/*.tsx"],
81+
"exclude": ["./node_modules/**/*"]
82+
}
83+
```
84+
85+
#### 5.babel-core版本v6.x
86+
<pre>
87+
Error: You gave us a visitor for the node type "TSDeclareFunction" but it's not a valid type (While processing preset: "/Users/nojvek/mp/insights/node_modules/babel-preset-typescript/lib/index.js")
88+
</pre>
89+
将babel-core升级为[email protected]才能处理TSDeclareFunction版本号。具体可以参看该babel的[issue](https://github.com/babel/babel/issues/6392)。此时就可以使用下面的代码:
90+
```js
91+
const babel = require("babel-core");
92+
// app.tsx
93+
fs.readFile("./app.tsx", (err, data) => {
94+
if (err) throw err;
95+
const compiled = babel.transform(data.toString(), {
96+
presets: ["typescript"]
97+
});
98+
});
99+
```
100+
101+
#### 6.babylon解析flow和typescript不能同时出现
102+
<pre>
103+
Cannot combine flow and typescript plugins.
104+
</pre>
105+
下面是babylon检验代码:
106+
```js
107+
if (pluginList.indexOf("flow") >= 0 && pluginList.indexOf("typescript") >= 0) {
108+
throw new Error("Cannot combine flow and typescript plugins.");
109+
}
110+
```
111+
去掉flow插件即可:
112+
```js
113+
const babylon = require("babylon");
114+
const types = require("babel-types");
115+
const traverse = require("babel-traverse").default;
116+
function parser(content) {
117+
return babylon.parse(content, {
118+
sourceType: "module",
119+
plugins: [
120+
"classProperties",
121+
"estree",
122+
"jsx",
123+
// "flow",
124+
// 这里注释掉
125+
"typescript",
126+
// 通过这种方式babylon就支持typescript了
127+
// 但是babel相关插件需要升级到v7.0+
128+
"doExpressions",
129+
"objectRestSpread",
130+
"decorators",
131+
"decorators2",
132+
"classPrivateProperties",
133+
"classPrivateMethods",
134+
"exportExtensions",
135+
"asyncGenerators",
136+
"functionBind",
137+
"functionSent",
138+
"dynamicImport",
139+
"numericSeparator",
140+
"optionalChaining",
141+
"importMeta",
142+
"bigInt",
143+
"optionalCatchBinding",
144+
"throwExpressions",
145+
"pipelineOperator",
146+
"nullishCoalescingOperator"
147+
]
148+
});
149+
}
150+
module.exports = parser;
151+
```
152+
上面是相关babylon的版本配置:
153+
```js
154+
{
155+
"dependencies": {
156+
"@babel/plugin-proposal-class-properties": "^7.2.1",
157+
"@babel/plugin-syntax-class-properties": "^7.2.0",
158+
"@babel/plugin-syntax-object-rest-spread": "^7.2.0",
159+
"@babel/plugin-transform-typescript": "^7.2.0",
160+
"@babel/preset-typescript": "^7.1.0",
161+
"babel-core": "^7.0.0-beta.3",
162+
"babel-preset-typescript": "^7.0.0-alpha.19",
163+
"babylon": "^7.0.0-beta.47"
164+
}
165+
}
166+
```
167+
#### 7.需要开启classProperties属性
168+
<pre>
169+
SyntaxError: unknown: This experimental syntax requires enabling the parser plugin: 'classProperties' (28:4)
170+
</pre>
171+
当时以为需要如下方式引入plugin:
172+
```js
173+
"@babel/plugin-proposal-class-properties",
174+
"@babel/proposal-class-properties",
175+
"@babel/plugin-syntax-class-properties",
176+
["@babel/plugin-proposal-class-properties", { loose: true }],
177+
"@babel/plugin-proposal-object-rest-spread"
178+
```
179+
其实并不是,只要添加classProperties即可。具体查看[babylon](https://web.npm.alibaba-inc.com/package/babylon)插件。
180+
181+
#### 8.babylon解析typescript异常
182+
<pre>
183+
/Users/xxx/Desktop/hub-kit-cnt-ts/node_modules/[email protected]@babylon/lib/index.js:775
184+
throw err;
185+
^
186+
187+
SyntaxError: Unexpected token (3:17)
188+
</pre>
189+
此时将babylon升级为如下版本即可:
190+
```js
191+
"babylon": "^7.0.0-beta.47"
192+
```
193+
194+
#### 9.babel-generator解析异常无法回归源码
195+
```js
196+
"use strict";
197+
const babylon = require("babylon");
198+
const types = require("babel-types");
199+
const util = require("util");
200+
const fs = require("fs");
201+
const generator = require("babel-generator").default;
202+
const traverse = require("babel-traverse").default;
203+
function parser(content) {
204+
return babylon.parse(content, {
205+
sourceType: "module",
206+
plugins: [
207+
"classProperties",
208+
"estree",
209+
"jsx",
210+
// "flow",
211+
"typescript",
212+
"doExpressions",
213+
"objectRestSpread",
214+
"decorators",
215+
"classPrivateProperties",
216+
"classPrivateMethods",
217+
"exportExtensions",
218+
"asyncGenerators",
219+
"functionBind",
220+
"functionSent",
221+
"dynamicImport",
222+
"numericSeparator",
223+
"optionalChaining",
224+
"importMeta",
225+
"bigInt",
226+
"optionalCatchBinding",
227+
"throwExpressions",
228+
"pipelineOperator",
229+
"nullishCoalescingOperator"
230+
]
231+
});
232+
}
233+
module.exports = function transformer(content) {
234+
let imports = [],
235+
exportNames = [],
236+
globalExportDefaultName = "",
237+
classExportsDefaultName = "",
238+
isClssDefaultExport = false;
239+
const inputAst = parser(content);
240+
const sourceCode = generator(inputAst, {}, content).code;
241+
// 这里我试过了很多版本的babel-generator都不行
242+
console.log(inputAst);
243+
};
244+
```
245+
上面试过了很多版本都不行,所以最后并没有通过babel-generator来完成,而是通过babylon解析,然后通过regex将不需要的代码replace掉。后面会继续关注该方面的知识点。
246+
<pre>
247+
throw new ReferenceError("unknown node of type " + (0, _stringify2.default)(node.type) + " with constructor " + (0, _stringify2.default)(node && node.constructor.name));
248+
^
249+
250+
ReferenceError: unknown node of type "Literal" with constructor "Node"
251+
at Generator.print (/Users/xxx/Desktop/hub-kit-cnt-ts/node_modules/[email protected]@babel-generator/lib/printer.js:279:13)
252+
at Generator.JSXAttribute (/Users/xxx/Desktop/hub-kit-cnt-ts/node_modules/[email protected]@babel-generator/lib/generators/jsx.js:28:10)
253+
at /Users/xxx/Desktop/hub-kit-cnt-ts/node_modules/[email protected]@babel-generator/lib/printer.js:298:23
254+
at Buffer.withSource (/Users/xxx/Desktop/hub-kit-cnt-ts/node_modules/[email protected]@babel-generator/lib/buffer.js:159:28)
255+
at Generator.withSource (/Users/xxx/Desktop/hub-kit-cnt-ts/node_modules/[email protected]@babel-generator/lib/printer.js:189:15)
256+
at Generator.print (/Users/xxx/Desktop/hub-kit-cnt-ts/node_modules/[email protected]@babel-generator/lib/printer.js:297:10)
257+
at Generator.printJoin (/Users/xxx/Desktop/hub-kit-cnt-ts/node_modules/[email protected]@babel-generator/lib/printer.js:366:12)
258+
at Generator.JSXOpeningElement (/Users/xxx/Desktop/hub-kit-cnt-ts/node_modules/[email protected]@babel-generator/lib/generators/jsx.js:108:10)
259+
at /Users/xxx/Desktop/hub-kit-cnt-ts/node_modules/[email protected]@babel-generator/lib/printer.js:298:23
260+
at Buffer.withSource (/Users/xxx/Desktop/hub-kit-cnt-ts/node_modules/[email protected]@babel-generator/lib/buffer.js:159:28)
261+
at Generator.withSource (/Users/xxx/Desktop/hub-kit-cnt-ts/node_modules/[email protected]@babel-generator/lib/printer.js:189:15)
262+
at Generator.print (/Users/xxx/Desktop/hub-kit-cnt-ts/node_modules/[email protected]@babel-generator/lib/printer.js:297:10)
263+
at Generator.JSXElement (/Users/xxx/Desktop/hub-kit-cnt-ts/node_modules/[email protected]@babel-generator/lib/generators/jsx.js:74:8)
264+
at /Users/xxx/Desktop/hub-kit-cnt-ts/node_modules/[email protected]@babel-generator/lib/printer.js:298:23
265+
at Buffer.withSource (/Users/xxx/Desktop/hub-kit-cnt-ts/node_modules/[email protected]@babel-generator/lib/buffer.js:159:28)
266+
at Generator.withSource (/Users/xxx/Desktop/hub-kit-cnt-ts/node_modules/[email protected]@babel-generator/lib/printer.js:189:15)
267+
at Generator.print (/Users/xxx/Desktop/hub-kit-cnt-ts/node_modules/[email protected]@babel-generator/lib/printer.js:297:10)
268+
at Generator.printJoin (/Users/xxx/Desktop/hub-kit-cnt-ts/node_modules/[email protected]@babel-generator/lib/printer.js:366:12)
269+
</pre>
270+
271+
272+
273+
274+
参考资料:
275+
276+
[babylon](https://github.com/babel/babylon/issues/320)
277+
278+
[typescript](https://github.com/Microsoft/TypeScript/issues/11441)
279+
280+

typescript/function.md

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
### 备注
2+
该部分只列举那些稍微难以理解的typescript的function相关内容,详细内容可以参考[TypeScript官网](http://www.typescriptlang.org/docs/handbook/functions.html)
3+
4+
### 1.typescript的function
5+
```js
6+
// myAdd has the full function type
7+
let myAdd = function(x: number, y: number): number { return x + y; };
8+
// The parameters 'x' and 'y' have the type number
9+
// 函数必须有参数和返回值,宽箭头之前是参数,之后是返回值
10+
let myAdd: (baseValue: number, increment: number) => number =
11+
function(x, y) { return x + y; };
12+
```
13+
14+
### 2.可选和默认参数
15+
在TypeScript中,每一个参数都被认为是必须的,但是可以是null或者undefined。但是调用函数传入的参数数量必须和函数本身期望的参数数量一致。
16+
```js
17+
function buildName(firstName: string, lastName: string) {
18+
return firstName + " " + lastName;
19+
}
20+
let result1 = buildName("Bob"); // error, too few parameters
21+
let result2 = buildName("Bob", "Adams", "Sr."); // error, too many parameters
22+
let result3 = buildName("Bob", "Adams"); // ah, just right
23+
```
24+
当然你也可以设置一个参数为可选,比如下面的lastName,可以通过**?**修饰:
25+
```js
26+
function buildName(firstName: string, lastName?: string) {
27+
if (lastName)
28+
return firstName + " " + lastName;
29+
else
30+
return firstName;
31+
}
32+
let result1 = buildName("Bob");
33+
// works correctly now
34+
let result2 = buildName("Bob", "Adams", "Sr.");
35+
// error, too many parameters
36+
let result3 = buildName("Bob", "Adams");
37+
// ah, just right
38+
```
39+
也可以通过如下方式设置默认值,此时用户**不传入或者传入的是null也会被设置为默认值**:
40+
```js
41+
function buildName(firstName: string, lastName = "Smith") {
42+
return firstName + " " + lastName;
43+
}
44+
let result1 = buildName("Bob");
45+
// works correctly now, returns "Bob Smith"
46+
let result2 = buildName("Bob", undefined);
47+
// still works, also returns "Bob Smith"
48+
// 即使用户传入了undefined或者null也会返回默认值~
49+
let result3 = buildName("Bob", "Adams", "Sr.");
50+
// error, too many parameters
51+
let result4 = buildName("Bob", "Adams");
52+
// ah, just right
53+
```
54+
所有必选参数后面的默认实例化的参数都被认为是可选的,和可选参数一样,在调用的时候可以忽略。同时,可选参数和默认参数的type被认为和前一个必选参数是一样的:
55+
```js
56+
function buildName(firstName: string, lastName?: string) {
57+
// ...
58+
}
59+
```
60+
和下面的函数:
61+
```js
62+
function buildName(firstName: string, lastName = "Smith") {
63+
// ...
64+
}
65+
```
66+
的类型都是如下格式:
67+
```js
68+
(firstName: string, lastName?: string) => string
69+
```
70+
71+
### 3.Rest参数
72+
```js
73+
function buildName(firstName: string, ...restOfName: string[]) {
74+
return firstName + " " + restOfName.join(" ");
75+
}
76+
// 在js中使用arguments
77+
let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie");
78+
```
79+
也可以通过如下方式书写:
80+
```js
81+
function buildName(firstName: string, ...restOfName: string[]) {
82+
return firstName + " " + restOfName.join(" ");
83+
}
84+
let buildNameFun: (fname: string, ...rest: string[]) => string = buildName;
85+
// 前面是参数和返回值
86+
```
87+

0 commit comments

Comments
 (0)