Running typescript app with pm2 and tsx

You can run node server apps in pm2 with ts-node just by simply declaring it as dependency. As always there is a catch, ts-node by default use typescript compiler to typecheck and then run the code. There is way to disable typechecking via tsconfig.json file.

{
  "extends": "ts-node/node16/tsconfig.json",
  "ts-node": {
    "transpileOnly": true,
    "files": true,
    "compilerOptions": {}
  },
  "compilerOptions": {
    // typescript options here
  }
}

Reference: https://www.npmjs.com/package/ts-node#via-tsconfigjson-recommended

I had assumed ts-node had no way to disable typechecking and looked at tsx instead. But there is a reasonable argument for using tsx if you have large node application since tsx uses esbuild under the hood.

There are two ways to run a typescript program with tsx.

tsx index.ts

# or

node --import tsx index.ts

pm2 allows you configure the interpreter it uses run the files. So in ecosystem.config.js you can configure you application as follows

module.exports = {
  apps: [
    {
      name: "server",
      script: "./server/index.ts",
      interpreter: "tsx",
    },
  ],
};

I couldn’t get this work locally as tsx needs to be in PATH environment variable since I was using volta. Therefore, I turned to the latter style and it works

module.exports = {
  apps: [
    {
      name: "server",
      script: "./server/index.ts",
      interpreter: "node",
      interpreterArgs: "--import tsx",
    },
  ],
};

For Node 18 and below, you should use –loader instead of –import.