Skip to content

Node + Typescript 搭建项目基础框架

创建项目目录

bash
mkdir MyProjret && cd MyProject

配置 TypeScript 编译环境

tsc是 TypeScript 编译器的命令行工具,它用于将 TypeScript 代码编译(或转译)成 JavaScript 代码 (默认已安装了 Node 和 TypeScript 环境)

bash
tsc --init

执行上面的命令后会看到在 MyProject目录下创建 tsconfig.json文件,当编译 TypeScript 文件时,会根据 tsconfig.json 配置文件进行编译项目。

tsconfig.json 有很多的编译配置项,目前只关注下面两个选项:

  • rootdir - 指定 Typescript 源文件中的根文件夹
  • outdir - 指定 Typescript 编译后输出文件夹

对于 rootdir选项:

bash
"rootdir": "./src"

对于 outdir选项:

bash
"outdir": "./build"

创建 TypeScript 文件

创建 src源码目录:

bash
mkdir src cd src

创建 TypesScript文件:

bash
touch app.ts

写入 code

bash
cat > app.ts

然后输入一段日志:

typescript
const message: string = "hello world"
console.log(message)

运行 Typescript 文件

编译:

bash
tsc

运行:

bash
node ./build/app.js

基于 Node 构建自动化工作流

上述的完成了一个 TypeScript 项目的开发环境配置,但是每次源码修改都需要重新手动执行 tsc 将 TypeScript 变异为 JavaScript 源码,再运行。 我们可以使用 Node.js 构建一个自动化的

安装 Node modules

bash
npm init

开发调试 TypeScript

安装 tsx

tsx 是一个用于 TypeScript 的运行时工具,快速运行 TypeScript 文件而不需要事先编译

bash
npm install -D tsx

在项目中使用 tsx 在 package.json 中添加脚本使用 tsx 运行 TypeScript

json
{
	"scripts": {
		"dev": "tsx ./src.app.ts"
	}
}

也设置为 tsx -w ,表示 **watch **模式。在这种模式下, tsx 会监视指定的文件,当文件发生变化时自动重新运行。对于开发过程中实时查看更改非常有用。

json
{
	"scripts": {
		"dev": "tsx -w ./src.app.ts"
	}
}

编译 TypeScript

  • 运行 tsc 会读取 tsconfig.json文件中的配置,将 TypeScript 代码编译成 JavaScript。(如上述例子中的 outdir配置,会将编译后的文件输出该配置的文件夹下)
  • 也可以运行 tsc -w ,表示 watch 模式,TypeScript 编译器会监视所有 TypeScript 文件的变化,并在文件发生变化时自动重新编译。
json
{
	"scripts": {
		"build": "tsc",
		"build:watch": "tsc -w"
	}
}

运行编译后的 JavaScript

json
{
	"scripts": {
		"start": "node ./build/app.js"
	}
}

也使用 nodemon运行编译后的 JavaScript 源码,nodemon会在 JavaScript 源码发生改变时自动重新启动应用 安装 nodemon

bash
npm install -g nodemon

使用 nodemon 运行 JavaScript 源码

json
{
	"scripts": {
		"start": "nodemon ./build/app.js"
	}
}

配置自动化编译运行的工作流

如何想实现在修改 TypeScript 源码时,自动的编译为 JavaScript、并且运行,我们可以

json
{
	"scripts": {
		"start:build": "tsc -w",
		"start:run": "nodemon ./build/app.js",
		"start": "concurrently npm:start:*"
	}
}

concurrently工具可以运行多个命令,concurrently npm:start:*标识运行以 start:开头的脚本 这样我们实现了自动化的编译运行的工作流:

  1. 同时运行编译、和运行脚本
  2. 监听 TypeScript 源码变动并实时编译为 JavaScript
  3. 监听 JavaScript 源码变动并实时的重启应用

Released under the MIT License.