# 快速创建 TypeScript 项目

# 1. node.js 中使用 TS

步骤:

npm init -y

npm i -D typescript

npm i -D @types/node

# 创建 tsconfig.json 文件
npx tsc --init

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
  },
  "include": [
    "src"
  ]
}

实时编译和运行:

npm i -D ts-node

npm i -D nodemon

package.json:

{
  "scripts": {
    "start": "npm run build:live",
    // 编译时,在当前目录查找 tsconfig.js 文件
    "build": "tsc -p .",
    "build:live": "nodemon --watch 'src/**/*.ts' --exec 'ts-node' src/index.ts"
  }
}

# 2. 浏览器中使用 TS

tsconfig.json:

{
  "compilerOptions": {
    "sourceMap": true,
    
    "target": "es5",

    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    
    "module": "esnext",
    "moduleResolution": "node",

    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,

    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
  },

  "include": [
    "src"
  ],
  "compileOnSave": false
}

# 3. TS 包

目录:

/
  src/        # 源码目录
    index.ts
  lib/        # 编译目录
    index.js

  package.json
  tsconfig.json

tsconfig.json:

{
  "compilerOptions": {
    // 输出目录
    "outDir": "lib",

    // 输出声明文件
    "declaration": true,
  },

  "include": [
    "./src/**/*"
  ],
}

package.json:

{
  // 告诉 node.js 加载 lib/index.js
  "main": "lib/index",

  // 告诉 ts 加载 lib/lib.index.d.ts
  "types": "lib/index",
}

typestyle:

本章目录