ts node项目配置esm支持

726 阅读1分钟

前言

对于nodejs来说,它本身的cjs规范对于ts的支持很差,对于现代的新nodejs,可以使用esm模块,以更好的对ts类型推导支持。

项目创建

那下面就让我们开始配置吧

$ mkdir node-esm
$ cd node-esm
$ yarn init -y
$ mkdir src
$ new-item src/app.ts
$ new-item tsconfig.json
$ code .

安装依赖

$ yarn add typescript tsconfig-paths ts-node nodemon @types/express -D
$ yarn add express --save

tsconfig.json

{
  "compilerOptions": {
    "module": "NodeNext", // 模块
    "target": "ES5",
    "moduleResolution": "NodeNext", // 模块解析
    "esModuleInterop": true, // 是否支持esm
    "strict": true,
    "noImplicitAny": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["src/**/*.ts", "src/*.ts"],
  "exclude": ["node_modules"]
}

nodemon.json

{
  "watch": ["src"], // 监听文件夹
  "ext": ".ts", // 文件扩展
  "exec": "ts-node -r tsconfig-paths/register src/app.ts" // 执行命令
}

package.json

  "scripts": {
    "start": "nodemon"
  },

效果

// src/app.ts
import express from "express"

const app = express()

app.listen(3000, () => {
  console.log("Server running on http://127.0.0.1:3000/")
})