Skip to content

TS 测试DEMO

初始化

bash
pnpm init
  • 生成package.json
bash
{
  "name": "ts",
  "version": "1.0.0",
  "description": "",
  "main": "index.ts",
  "scripts": {
    "dev": "tsx src/demo/index.ts"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/node": "^25.0.6",
    "ts-node": "^10.9.2"
  }
}

安装依赖

bash
pnpm add typescript ts-node @types/node -D

创建 tsconfig.json

  • 根目录创建tsconfig.json
json
{
  "compilerOptions": {
    /* 语言与环境 */
    "target": "ES2020", // 编译后的 JS 版本 (ES2020 比较现代)
    "module": "commonjs", // 模块系统 (Node.js 项目通常用 commonjs)
    "lib": ["ES2020"], // 引入的库定义

    /* 输出配置 */
    "outDir": "./dist", // 编译后的 JS 文件存放目录
    "rootDir": "./src", // 源代码 (.ts 文件) 的根目录
    "removeComments": true, // 编译时删除注释
    "noEmitOnError": true, // 报错时不生成编译文件

    /* 类型检查 (严格模式) - 建议开启,能帮你找错 */
    "strict": true, // 启用所有严格类型检查选项
    "esModuleInterop": true, // 允许 import 导入 CommonJS 模块
    "skipLibCheck": true, // 跳过对库文件的类型检查 (加快编译速度)
    "forceConsistentCasingInFileNames": true // 强制文件名大小写一致
  },
  "include": ["src/**/*"], // 只编译 src 目录下的文件
  "exclude": ["node_modules"] // 排除 node_modules 目录
}

编写代码

  • src/demo/index.ts
ts
let a: string = "测试今天";
console.log(a);

运行

bash
npm run dev