PM2 — Use TSX to Start Your App

We migrated the code running the superchargejs.com website from CommonJS to ESM. The CommonJS project used ts-node in combination with SWC to run the code. But ts-node isn’t working with TypeScript and ESM (there’s an open issue).

We can’t use ts-node because of the mentioned issue and found an alternative: tsx. tsx comes as a CLI or module loader that runs your TypeScript with ESM codebase. That’s what we need!

This tutorial shows you how to configure PM2 to run your application with tsx.

PM2 Series Overview

PM2 Configuration to Run Your App with TSX

PM2 is a daemon process manager that keeps your application alive in a long-running background process on a given system. You can configure PM2 via the command line interface or an explicit configuration file. We recommend using the configuration file to surface the options used to start your app.

We installed tsx globally on our server to have the same-named tsx command available in the terminal. That means Node.js can use tsx as a Node.js customization hook to handle TypeScript files that use ESM. You’re passing customization hooks (previously called loader or require hooks) as arguments to the node interpreter. Use PM2’s interpreter_args option to tell Node.js about tsx hook:

module.exports = {  
  name: 'superchargejs.com',

  script: 'server.ts',
  interpreter: 'node',
  interpreter_args: '--import tsx',

  exec_mode: 'cluster',
  instances: 2,

  // other PM2 configuration options
}

And PM2 cluster mode works nicely with tsx too! Running apps in PM2 cluster mode is connected to Node.js as the interpreter. Using tsx as the interpreter would remove the ability to start your application in cluster mode. PM2 uses Node.js’ cluster module to scale your clustered application. Using a different interpreter than Node.js forces your app to start in PM2 fork mode. That’s the reason you should use tsx as a customization hook and keep the PM2 zero-downtime restarts.

Enjoy using tsx with PM2!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.