一、项目构建

  • 1、创建文件夹并且初始化

    npm init -y
    
  • 2、安装babel依赖包

    yarn add @babel/cli @babel/core @babel/preset-env  @babel/preset-typescript typescript -D
    
  • 3、在项目下创建一个babel.config.js文件

    module.exports = {
      presets: [
        [
          '@babel/preset-env',
          {
            targets: {
              node: 'current',
            },
          },
        ],
        '@babel/preset-typescript',
      ],
    };
    
  • 4、初始化ts的配置文件,关于配置文件的内容就不介绍,有兴趣的可以参考

    tsc --init
    
    {
      "compilerOptions": {
        "target": "es5",                     
        "module": "commonjs", 
        "strict": true,    
        "esModuleInterop": true,  
        "skipLibCheck": true,                    
        "forceConsistentCasingInFileNames": true 
      },
      "include": [
        "src"
      ]
    }
    
  • 5、在package.json中配置编译命令

    "scripts": {
      "babel": "babel src --out-dir dist --extensions \".ts\""
    },
    
  • 6、开心的写typescript代码

二、使用typescript搭建express项目

  • 1、初始化项目

    npm init -y
    tsc --init
    
  • 2、修改tsconfig.json文件内容

    {
      "compilerOptions": {
        "target": "es5",                                
        "module": "commonjs", 
        "outDir": "./dist",                          
        "strict": true,                                 
        "esModuleInterop": true,                   
        "skipLibCheck": true,                           
        "forceConsistentCasingInFileNames": true,
        "baseUrl": "src"        
      },
      "exclude": ["node_modules"],
      "include": ["./src/**/*.ts"]
    }
    
  • 3、安装express的依赖包

    yarn add express
    yarn add @types/express
    
  • 4、在src/index.ts文件中书写代码

    import express, { Express, Request, Response, NextFunction } from 'express';
    const PORT: number = 3000;
    const app: Express = express();
    
    app.get('/', async (req: Request, res: Response, next: NextFunction) => {
      res.json({
        code: 0,
        message: 'success',
      });
    });
    
    app.listen(PORT, () => {
      console.log(`服务已经启动:localhost:${PORT}`);
    });
    
  • 5、在package.json中配置启动命令

    "scripts": {
      "build": "tsc",
      "start": "ts-node-dev --respawn src/index.ts",
      "dev": "nodemon --exec ts-node --files src/index.ts"
    },
    

    开发环境启动命令可以是用dev或者start,如果你要使用start启动方式就要多安装两个依赖包

    yarn add ts-node-dev typescript -D
    
Logo

一站式 AI 云服务平台

更多推荐