Tuesday, December 3, 2024
HomeEveryday WordPressHow to set up TypeScript with Express

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 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"
        // …
      }
    }



Source link

RELATED ARTICLES
Continue to the category

LEAVE A REPLY

Please enter your comment!
Please enter your name here


Most Popular

Recent Comments