PM2 运行Typescript项目

2,695 阅读1分钟

PM2 部署Node、Typescript项目

环境:

node: 14.18.0
typescript: 4.9.5
ts-node:10.9.1
pm2:5.2.2

背景

最近在准备写一些小demo,搭建node项目时使用nodeTypeScript配合开发

在搭建完基本结构以及依赖安装后,最初是采取直接通过nodemon运行的,主要是对Typescript的支持很棒,装完ts-node 后可以直接通过

nodemon index.ts

来接直接运行ts编写的代码,到这一步项目都是能完全跑通的。

对了,为了更方便建议去掉 package.json中的type属性。

将tsconfig.ts中的module改为CommonJs同样能使用 ESModule

项目初始化基本完善,需要提前考虑部署,这里选用了pm2作为部署

在运行前需要将typescript安装到pm2的node_modules下

pm2 install typescript

安装成功后还需要一个注意的点就是要将pm2的mode改为cluster模式, 否则就可能出现下方错误

# Error: spawn ..\Roaming\npm\node_modules\pm2\node_modules\.bin\ts-node ENOENT

至于为什么可以看看这里issue

不过这里建议通过PM2的配置文件来启动更加方便

pm2 start ecosystem.config.js

下面是配置文件

tsconfig.ts

{
  "compilerOptions": {
    "module": "CommonJS", //指定生成哪个模块系统代码
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "target": "ES2016", //目标代码类型
    "noImplicitAny": true, //在表达式和声明上有隐含的'any'类型时报错。
    "moduleResolution": "node",
    "sourceMap": true, //用于debug   
    "baseUrl": ".",
    "experimentalDecorators": true,
    "outDir": "./dist",
    "rootDir": "./"
  },
  "exclude": [
    "node_modules/**/*"
  ],
  "include": [
    "**/**/*"
  ]
}

econsystem.config.js

module.exports = {
  apps: [
    {
      name: "socket",
      script: "./index.ts",
      interpreter: "./node_modules/.bin/ts-node",
      exec_mode: "cluster",
    },
  ],
};