myesn

myEsn2E9

hi
github

Node.js: v18.x 快速集成 TypeScript + ESM + Strictest

  1. mkdir tests && cd tests
  2. yarn init -y
  3. yarn global add typescript ts-node
  4. yarn add -D @tsconfig/node18-strictest-esm typescript ts-node tslib @types/node concurrently nodemon
    参考
  5. 创建 tsconfig.json 文件,并添加以下配置:
    {
      "extends": "@tsconfig/node18-strictest-esm/tsconfig.json",
      "compilerOptions": {
        "baseUrl": ".",
        "rootDir": "src",
        "outDir": "dist",
        "noImplicitAny": true,
        "removeComments": true,
        "sourceMap": true,
        "module": "CommonJS",
      },
      "include": [
        "src/**/*"
      ]
    }
    
  6. 在 package.json 文件中添加以下脚本:
"scripts": {
  "dev": "ts-node-esm src/index.ts",
  "build-ts": "tsc",
  "build": "yarn build-ts",
  "debug": "yarn build && yarn watch-debug",
  "serve-debug": "nodemon --inspect dist/index.js",
  "serve": "node dist/index.js",
  "start": "yarn serve",
  "watch-debug": "concurrently -k -p \"[{name}]\" -n \"TypeScript,Node\" -c \"yellow.bold,cyan.bold,green.bold\" \"npm:watch-ts\" \"npm:serve-debug\"",
  "watch-node": "nodemon dist/index.js",
  "watch-ts": "tsc -w",
  "watch": "concurrently -k -p \"[{name}]\" -n \"TypeScript,Node\" -c \"yellow.bold,cyan.bold,green.bold\" \"npm:watch-ts\" \"npm:watch-node\""
}

备注:

  • ts-node 为了开发环境不编译直接执行 ts 文件,比如 ts-node src/index.ts
  • tsconfig.json 中 "module": "CommonJS" 是为了 ts-node-esm 能够正常使用 ES Module 的方式 import 文件
  • tsconfig.json 中 "sourceMap": true 是为了生产 source map,使得 node dist/index.js 执行后可以调试 src/index.ts 的文件,如果使用 ts-node 可以不用配置这个

参考:https://www.cnblogs.com/myesn/p/15739730.html

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.