Loading

Node.js + TypeScript + ESM +HotReload ( TypeScript 类型的 Node.js 项目从 CommJS 转为 ESM 的步骤)

当前 Node.js 版本:v16.14.0
当前 TypeScript 版本:^4.6.3

步骤

安装必要的依赖

yarn add -D typescript ts-node @tsconfig/node16 @types/node nodemon

package.json 修改

{
  ...,
  "type": "module",
  "scripts": {
    "build": "tsc",
    "debug": "yarn build && nodemon --inspect src/main.ts",
    "go": "node --experimental-specifier-resolution=node dist/main.js"
  },
  "engines": {
    "node": ">=16.14.0"
  }
}

tsconfig.json 修改

{
  "extends": "@tsconfig/node16/tsconfig.json",
  "compilerOptions": {
    "baseUrl": ".",
    "rootDir": "src",
    "outDir": "dist",
    "noImplicitAny": true,

    "module": "ESNext",
    "moduleResolution": "node"
  },
  "include": ["src/**/*"]
}

nodemon.json 修改

注意,这里配置了环境变量,也就是说这里配置的环境变量优先级高于系统环境变量

{
  "restartable": "rs",
  "ignore": [".git", "node_modules/**/node_modules"],
  "verbose": true,
  "execMap": {
    "ts": "node --experimental-specifier-resolution=node --loader ts-node/esm"
  },
  "watch": ["src/", ".env"],
  "env": {
    "NODE_ENV": "development"
  },
  "ext": "js,json,ts"
}

参考

posted @ 2022-04-13 10:07  myEsn2E9  阅读(159)  评论(0编辑  收藏  举报