CLI
sh
tsc
# watch mode
tsc --watch
# 仅编译 index.ts 文件
tsc index.ts
# 编译 src 文件夹下的所有 ts 文件
tsc src/*.ts
# 指定编译配置文件
tsc --project tsconfig.production.jsontsconfig.json
Node12
json
{
"$schema": "https://json.schemastore.org/tsconfig",
"display": "Node 12",
"compilerOptions": {
"lib": ["es2019", "es2020.promise", "es2020.bigint", "es2020.string"],
"module": "commonjs",
"target": "es2019",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node"
}
}json
{
"compilerOptions": {
"target": "es6",
"moduleResolution": "node",
"module": "commonjs",
"strict": true,
"declaration": true,
"noUnusedLocals": true,
"esModuleInterop": true
}
}module:用来指定要使用的模块化规范"None", "CommonJS", "AMD", "System", "UMD", "ES6"或 "ES2015"。moduleResolution: 模块处理策略。或者是"Node"对于 Node.js/io.js,或者是"Classic"(默认)。target:指定编译出来的 ECMAScript 目标版本 "ES3"(默认), es3, es5, es6/es2015, es2016, es2017, es2018, es2019, es2020, es2021, es2022, or esnextdeclaration: 生成相应的 .d.ts 文件。noUnusedLocals: 若有未使用的局部变量则抛错。
alias
json
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@/*": ["./src/*"],
"@@/*": ["./src/*"],
"~/*": ["./src/*"],
"~~/*": ["./src/*"]
}
}
}TypeScript & ESM
用 esbuild 增强 Node.js 以执行 TypeScript & ESM 文件
安装 tsx
sh
# 全局安装
pnpm add -g tsx
# 安装为开发依赖
pnpm add -D tsx执行 TypeScript / ESM / CJS 模块
sh
tsx ./file.ts默认读取当前工作目录下的 tsconfig.json 配置文件,使用--tsconfig 自定义配置文件路径
sh
tsx --tsconfig ./path/to/tsconfig.custom.json ./file.ts执行文件,并在文件被修改后重新执行(watch mode)
sh
tsx watch ./file.ts所有导入的文件都会被监听,除了以下文件夹中的文件: node_modules, bower_components, vendor, dist, 和 .* (隐藏目录 )