Chuyển đến nội dung chính

第 4 課:Node.js 中的 TypeScript 和現代 JavaScript

Node.js、tsx/ts-node 的 TypeScript 設定。類型安全配置、路徑別名。 ESBuild/SWC 編譯。 Node.js 類型剝離(--experimental-strip-types)。裝飾器、元資料。

💻 程式設計 — 第 4 課 第 4 課:TypeScript 和現代 JavaScript 在 Node.js 中

Node.js 核心:從基礎到高級

第 1 部分:Node.js 內部結構

亞洲開發網

1. Node.js 的 TypeScript 設定

pnpm add -D typescript @types/node tsx
npx tsc --init
// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2023",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "outDir": "dist",
    "rootDir": "src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "declaration": true,
    "sourceMap": true,
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["src"],
  "exclude": ["node_modules", "dist"]
}

2. Node.js 類型剝離 (22+)

# Chạy TypeScript trực tiếp — không cần biên dịch
node --experimental-strip-types src/app.ts

# Hạn chế: không hỗ trợ enums, namespaces, decorators
# Chỉ strip types, không transform syntax

3. tsx — TypeScript 執行

// package.json
{
  "scripts": {
    "dev": "tsx watch src/app.ts",
    "start": "node dist/app.js",
    "build": "tsc",
    "typecheck": "tsc --noEmit"
  }
}
// src/app.ts
import { createServer } from 'node:http'

interface Config {
  port: number
  host: string
}

const config: Config = {
  port: Number(process.env.PORT) || 3000,
  host: process.env.HOST || '0.0.0.0',
}

const server = createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' })
  res.end(JSON.stringify({ status: 'ok', timestamp: Date.now() }))
})

server.listen(config.port, config.host, () => {
  console.log(`Server running at http://${config.host}:${config.port}`)
})

4. 路徑別名

// src/utils/logger.ts
export function log(message: string) {
  console.log(`[${new Date().toISOString()}] ${message}`)
}

// src/app.ts — dùng alias
import { log } from '@/utils/logger'
log('Server started')
# tsx hỗ trợ paths aliases tự động
# Với tsc build, cần tsc-alias
pnpm add -D tsc-alias

5. 使用 ESBuild/SWC 構建

// build.ts
import { build } from 'esbuild'

await build({
  entryPoints: ['src/app.ts'],
  bundle: true,
  platform: 'node',
  target: 'node22',
  outdir: 'dist',
  format: 'esm',
  sourcemap: true,
  external: ['pg', 'redis'], // Không bundle native modules
})

6. 裝飾器(第 3 階段)

// Decorators — TC39 Stage 3, Node.js native support
function log(target: any, context: ClassMethodDecoratorContext) {
  return function (this: any, ...args: any[]) {
    console.log(`Calling ${String(context.name)} with`, args)
    const result = target.apply(this, args)
    console.log(`Result:`, result)
    return result
  }
}

class Calculator {
  @log
  add(a: number, b: number) {
    return a + b
  }
}

下一篇: 檔案系統和路徑 — fs/promises、檔案監視、原子寫入。