How to set up TypeScript with Express

TypeScript is a strongly typed programming language that extends JavaScript capabilities. It offers a range of features to help you develop scalable applications with Node.js and Express.

One of the critical advantages of TypeScript over JavaScript is that it provides type classes, making it easier to write more predictable and maintainable code. Additionally, TypeScript offers type safety, ensuring your code is free from runtime errors and making detecting flaws early in development easier. The language also comes with refactoring tools and autocompletion, which improves developers’ experience.

Moreover, Node.js and Express provide excellent performance for applications of any scale. Using classes in TypeScript also helps with organization and structure, further aiding in scalability. With these tools, you can build robust and scalable applications to handle growing demand.

This article demonstrates setting up an Express application using TypeScript with a single endpoint. Then, it explains how to deploy your application to Kinsta’s application hosting.

How to create an Express server

To follow this tutorial, ensure you have Node.js and npm installed on your computer. To set up an Express server:

  1. Create a directory using the code below:
    mkdir sample_app && cd sample_app
  2. Initialize a Node.js application in the directory by running this command:
    npm init -y

    The -y flag in the command accepts the default prompts when creating a package.json file populated with the following code:

    { 
      "name": "sample_app",
      "version": "1.0.0",
      "description": "", 
      "main": "index.js", 
      "scripts": { 
        "test": "echo /"Error: no test specified/" && exit 1" 
      }, 
      "keywords": [], 
      "author": "", 
      "license": "ISC" 
    }
  3. Next, install express for adding essential functionality and dotenv for environment variable management in the directory you just created by running this command:
    npm i express dotenv
  4. Create a .env file in the root of the sample_app directory and populate it with the variable below.
    PORT=3000
  5. Create an express application that responds with a Hello World text when users visit http://localhost:3000.
    const express = require("express");
    const dotenv = require("dotenv");
    
    // configures dotenv to work in your application
    dotenv.config();
    const app = express();
    
    const PORT = process.env.PORT;
    
    app.get("/", (request, response) => { 
      response.status(200).send("Hello World");
    }); 
    
    app.listen(PORT, () => { 
      console.log("Server running at PORT: ", PORT); 
    }).on("error", (error) => {
      // gracefully handle error
      throw new Error(error.message);
    })

    dotenv.config() populates your Node application’s process environment (process.env) with variables defined in a .env file.

  6. Start your Node.js application by running this command:
    node index.js

    Check if the application works by visiting http://localhost:3000 on your browser. You should get a response similar to this.

    Hello World server with Express
    Hello World on http:localhost:3000.

Enable TypeScript in an Express application

Follow the steps below to use TypeScript in an Express application:

  1. Install TypeScript by running this command:
    npm i -D typescript

    The -D option enables npm to install packages as dev dependencies. You can use the packages you install with this option in the development phase.

  2. One of the strengths of the TypeScript community is the DefinitelyTyped GitHub repository. It stores documentation of type definitions for various npm packages. Users can quickly integrate npm packages into their projects without worrying about type-related difficulties by only installing the type definition for those packages with npm.DefinitelyTyped is an indispensable tool for TypeScript developers. It enables them to write cleaner and more efficient code and reduce the likelihood of errors. You install the type definitions of both express and dotenv by running this command:
    npm install -D @types/express @types/dotenv
  3. To initialize TypeScript, run this command.
    npx tsc --init

    The generated tsconfig.json file indicates your TypeScript application’s root directory. It provides configuration options to define how TypeScript compilers should work. It includes a series of config options disabled or enabled, with comments explaining each option.

  4. Add an outDir property to the config object to define the output directory.
    {
      "compilerOptions": {
        // …
        "outDir": "./dist"
        // …
      }
    }

How to create a TypeScript server

To create a TypeScript server, change the .js extension to .ts and update the code with these type definitions:

import express, { Request, Response } from "express";
import dotenv from "dotenv";

// configures dotenv to work in your application
dotenv.config();
const app = express();

const PORT = process.env.PORT;

app.get("/", (request: Request, response: Response) => { 
  response.status(200).send("Hello World");
}); 

app.listen(PORT, () => { 
  console.log("Server running at PORT: ", PORT); 
}).on("error", (error) => {
  // gracefully handle error
  throw new Error(error.message);
});

To use the compiler package and compile the TypeScript file into JavaScript, run the command below in the root directory of your application.

npx tsc

Then start your application by running the command.

node dist/index.js

Visiting http://localhost:3000 on your browser should provide a “Hello World” response.

How to deploy your TypeScript server to Kinsta

Now, you’re ready to deploy your application to the web. You can deploy your application to many platforms, including Kinsta’s application hosting.

Before you push your application to a Git repository, using TypeScript and committing the compiled JavaScript file to Git isn’t advisable. Include a start script in the package.json file.

{
  // …
  "script": {
    "start": "npx tsc && node dist/index.js",
  }
  // …	
}

Also, create a .gitignore file in your application’s root directory and include node_modules and .env to prevent pushing these files to your Git provider.

Once your repository is set, follow these steps to deploy your application to Kinsta:

  1. Log in or create an account to view your MyKinsta dashboard.
  2. Authorize Kinsta with your Git provider.
  3. Click Applications on the left sidebar, then click Add application.
  4. Select the repository and the branch you wish to deploy from.
  5. Assign a unique name to your app and choose a Data center location.
  6. Use all default configurations. MyKinsta uses npm start as the entry point to deploy your application. If you want to use another command, you can adjust the runtime process in MyKinsta.
  7. Click Create application.

After deployment, MyKinsta provides a URL to access your application deployment publicly. You can visit the page to confirm it displays “Hello World.”

Summary

This guide demonstrated how to develop and set up an Express Application using TypeScript and deploy the application with Kinsta. TypeScript has extra capabilities that JavaScript does not — including type classes, type safety, refactoring tools, and auto-completion — to help you build scalable applications and catch errors during development.

Kinsta helps you deploy your application fast with enhanced security and stability. With 27 data centers offering Google’s C2 machine, which runs on Google’s premium-tier network.

Have you used TypeScript in the past? What are your thoughts on using it with an Express server?

The post How to set up TypeScript with Express appeared first on Kinsta®.

版权声明:
作者:Zad
链接:https://www.techfm.club/p/105747.html
来源:TechFM
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>