To run a TypeScript application on a server, you have two primary environments to manage: development (where you want instant code reloads) and production (where you need compiled, optimized, and stable execution). [1, 2]
Here is the complete step-by-step guide to setting up and running your server-side TypeScript app using Node.js. [1]
Step 1: Initialize Project & Install Dependencies
First, create your project folder, set up Node.js, and install TypeScript along with the necessary type definitions. [1, 3]
Step 2: Configure TypeScript (tsconfig.json)
Generate a configuration file to tell the TypeScript compiler how to handle your code. [1, 4]
Open the generated
tsconfig.json and ensure the following core options are set: [1] "target": "ES2022"(or your preferred modern ECMAScript version)"module": "CommonJS"(standard for Node.js)"rootDir": "./src"(where your source TypeScript files live)"outDir": "./dist"(where the compiled JavaScript files will go) [1, 3]
Create a
src directory and add your main entry file, such as src/index.ts. [3, 5] Step 3: Running in Development Mode
During development, compiling files manually every time you make a change is slow. You should use a tool like
tsx or ts-node combined with a watcher to run your TypeScript files directly and restart on changes. [1, 2, 6] - Install
tsx(a fast, modern alternative tots-node+nodemon): - Add a development script to your
package.json: - Run your development server: [3]
Step 4: Running in Production Mode
For a production environment, you should never run raw TypeScript directly. Instead, compile the code to native JavaScript first, then run it using Node.js for maximum performance and stability. [2, 7]
- Add build and start scripts to your
package.json: - Build your application (this compiles TypeScript into the
dist/folder): - Start the production server: [2, 5, 6]
Step 5: Keeping the Server Alive in Production
If you are running this app on a live server (like an AWS EC2 instance or a VPS), your app will stop if the terminal closes or the app crashes. Use a process manager like PM2 to keep it running continuously in the background. [8]
- Install PM2 globally on your server:
- Build your app, then start it with PM2 pointing to your compiled JavaScript: [8]
If you run into any setup issues, let me know:
- What framework are you using (e.g., Express, Fastify, NestJS, or native HTTP)?
- Are you deploying to a specific platform (e.g., Docker, AWS, Render, Vercel)? [3, 9, 10, 11]
I can help you customize your configurations to match!
0 Comments