在项目中使用 ts
安装:
npm install typescript –save-dev

ts 配置文件:
创建 tsconfig.json 文件,文件内容为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators":true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"target": "es2017",
"sourceMap":true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true
},
"include": [
"src/**/*"
],
"exclude": ["node_modules", "dist"]
}

编译应用(tsc)
将 src 中的 ts 文件编译好并放在 dist 目录中
命令:./node_modules/.bin/tsc

dist 文件解释:
d.ts 类型定义信息
.js.map 将编译之前和之后的文件联系在一块

require 报错
报错原因:
由于 node 出来的时候 js 还没有标准的模块引入系统,所以 node 采用了 common.js 的模块引入方式,ts 不识别 require 这种方式,而现在使用了 ts 后,就可以使用 js 的模块引入系统了。这里报错并不是不能使用 require 这种方式,只是说 ts 不知道它是什么,所以报错了。

解决方式:
安装类型定义,让 ts 知道 require 以及跟 node 相关的其他东西。
npm install @types/node –save-dev


使用 javascript 标准模块系统
将 const xx = require(‘xxx’)这种方式更换为 import xxx from ‘xxxx’

安装 express 的类型定义
使用 ts 后在编辑器中可能会有三个点的报错 比如在 import express from ‘express’ 这段代码中的 from ‘express’部分,原因是因为 ts 不认识这个包。

安装类型定义来识别:
npm install @types/express –save-dev


自动编译与重启
可以使用 nodemon,使用 ts 后可以使用 tsc-watch。

安装 tsc-watch:
npm install tsc-watch –save-dev

使用命令:
在 package.json 中新增一条自定义命令,名字可以叫 start:dev,具体的命令是 “./node_modules/.bin/tsc-watch –onSuccess \”node dist/main.js\”” 。 –onSuccess 选项表示编译之后要做什么事,这里的意思是编译成功后使用 node 运行 dist 目录下的 main.js 文件。如果配置了终端后可以省略命令前面的./node_modules/.bin/ 。

使用方法:npm run start:dev
在保存文件后,就会执行 tsc-watch,来重新编译文件


自动排版代码
使用 prettier 这个包和插件。

使用 prettier 包
安装包:npm install prettier –save-dev –save-exact
设置命令:在 package.json 文件中新增命令,名字可以是 format,具体的命令是 “./node*modules/.bin/prettier –write \”src/**/_.ts\””
创建配置文件:名字是.prettierrc 内容是

1
2
3
4
{
"singleQuote": true,
"trailingComma": "all"
}

使用命令排版:npm run format 就可以了。

vscode 中使用 prettier 插件
vscode 中使用 command+shift+x 打开扩展,搜索 prettier 并安装。
使用 command + ,打开设置,搜索 format on save,在出来的界面中将 format on save 这个选项勾上。这样保存文件后会自动排版代码。