使用babel配置typescript开发环境

一、项目构建

  • 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
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水痕01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值