首页
/ Node.js 和 TypeScript 项目教程

Node.js 和 TypeScript 项目教程

2024-09-01 17:41:41作者:胡易黎Nicole

1. 项目的目录结构及介绍

create-nodejs-ts/
├── src/
│   ├── index.ts
│   └── ...
├── dist/
│   └── ...
├── package.json
├── tsconfig.json
└── ...
  • src/: 包含所有的 TypeScript 源代码文件。
  • dist/: 包含编译后的 JavaScript 文件。
  • package.json: 项目的依赖和脚本配置文件。
  • tsconfig.json: TypeScript 编译器的配置文件。

2. 项目的启动文件介绍

项目的启动文件是 src/index.ts。这个文件通常包含应用程序的入口点,例如:

import express from 'express';

const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello TypeScript + Node.js + Express');
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

3. 项目的配置文件介绍

package.json

package.json 文件包含了项目的依赖、脚本和其他元数据。例如:

{
  "name": "create-nodejs-ts",
  "version": "1.0.0",
  "scripts": {
    "build": "tsc",
    "start": "node dist/index.js"
  },
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "typescript": "^4.3.5"
  }
}

tsconfig.json

tsconfig.json 文件定义了 TypeScript 编译器的选项和项目设置。例如:

{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true
  },
  "include": ["src"]
}

这些配置文件确保了项目能够正确编译和运行。

登录后查看全文
热门项目推荐