Home > Web Front-end > JS Tutorial > How to set up TypeScript with Node.js and Express

How to set up TypeScript with Node.js and Express

尊渡假赌尊渡假赌尊渡假赌
Release: 2024-12-31 10:42:55
forward
1005 people have browsed it

Creating a server with TypeScript using Node.js and Express is a good alternative to using JavaScript because it makes it easier to manage complex applications and helps when you need to collaborate with a distributed team of developers.

TypeScript offers benefits like:

  • Improved code strength and clarity when static typing
  • Enhanced collaboration and project scalability
  • Advanced tooling
  • IDE support
  • Broad compatibility

All of these benefits make TypeScript a great choice for a smoother development experience, especially in evolving projects.

In this article, we’ll explore a beginner-friendly way to configure TypeScript in an Express app, as well as gain an understanding of the fundamental constraints that accompany it. To follow along, you should have:

  • Node.js ≥ v18.x installed in your local development environment
  • Access to a package manager like npm, pnpm, or Yarn
  • Basic familiarity with Node.js and Express

Check out the GitHub repository for the source code; the main branch has the TypeScript project, and the JavaScript branch has the JavaScript version.

Creating a package.json file

Start by creating a new directory in your local development environment, and within it, use npm’s initializer command to create a package.json file. If you use a package manager other than npm, consider adhering to the init command provided by that specific package manager:

mkdir ts-node-expresscd ts-node-express/npm init -y
Copy after login

When initializing a package.json file in this manner, the --yes or -y flag utilizes the default settings configured by npm, bypassing the repeated questions asking for project details. The resulting package.json file might look similar to the one shown in the following image:

Default Package.JSON File

Because the entry point of our application will be src/index.js, which we will address in the upcoming sections, you should update the main field in the package.json file from index.js to src/index.js:

{
  "name": "ts-node-express",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  ...}
Copy after login

Creating a minimal server with Express

After initializing the package.json file, add the Express and DotEnv packages to the project. In the terminal window, run the following command, where npm i is an alias to npm install:

npm i express dotenv
Copy after login

The DotEnv package is used to read environment variables from a .env file. Instead of hardcoding environment-specific variables directly into the app, include them all in this file and utilize the DotEnv package to manage them.

For instance, to specify the port number for your server, create a file named .env in the root of the project directory. Inside this file, define an environment variable for PORT and set its value to 3000. Consider adding more environment-specific variables in this file in the future as needed:

# Add all of the environmental variables here instead of # embedding them directly in the app and utilize them # with the `DotEnv` package.PORT=3000
Copy after login

Then, create a directory called src at the project’s root to organize our application source files. Add a new file named index.js to it and populate it with the following code, including the previously defined environmental variable:

// src/index.jsconst express = require('express');const dotenv = require('dotenv');dotenv.config();const app = express();const port = process.env.PORT;app.get('/', (req, res) => {
  res.send('Express   TypeScript Server');});app.listen(port, () => {
  console.log(`[server]: Server is running at http://localhost:${port}`);});
Copy after login

The above code covers the essential steps for setting up a minimal Express server using plain JavaScript. For a more detailed explanation, refer to the documented version of this snippet.

To start the server, execute the command node src/index.js in the terminal. This will execute the code that we just added to the index.js file and should start a new server, as illustrated below:

Setting Up Express Server

The Express server is now up and running, offering a foundational setup for development with Express on Node.js. Next, let’s enhance it by incorporating TypeScript in the next section.

Installing TypeScript

We will begin by installing TypeScript as a development dependency. Additionally, we’ll install the @types declaration packages for Express and Node.js, which offer type definitions in the form of declaration files.

Declaration files, typically denoted with the .d.ts extension, serve as predefined modules that outline the structure of JavaScript values or the types present for the TypeScript compiler. These declaration files are available for libraries originally written in JavaScript, not TypeScript.

The DefinitelyTyped GitHub repository maintains the TypeScript type definitions for direct use in Node.js and other JavaScript projects, sparing you the effort of defining these types from scratch. To incorporate types or declaration files for a specific library or module, seek packages starting with the @types namespace.

Launch the terminal and install the packages described above using the following command:

npm i -D typescript @types/express @types/node
Copy after login

The -D, or --dev, flag directs the package manager to install these libraries as development dependencies.

Installing these packages will add a new devDependencies object to the package.json file, featuring version details for each package, as shown below:

{
  ...
  "devDependencies": {
    "@types/express": "^5.0.0",
    "@types/node": "^22.7.4",
    "typescript": "^5.6.2"
  },
  ...}
Copy after login

Generating the TypeScript configuration file: tsconfig.json

Every TypeScript project utilizes a configuration file to manage various project settings. The tsconfig.json file, which serves as the TypeScript configuration file, outlines these default options and offers the flexibility to modify or customize compiler settings to suit your needs.

The tsconfig.json file is usually placed at the project’s root. To generate this file, use the following tsc command, initiating the TypeScript Compiler:

npx tsc --init
Copy after login

Once you execute this command, you’ll notice the tsconfig.json file is created at the root of your project directory. This file contains the default compiler options, as depicted in the image below:

Tsconfig.JSON File

Upon opening the tsconfig.json file, you’ll notice several other commented-out compiler options. Among all of these options, compilerOptions is a mandatory field that must be specified. Here’s a summary of all the default options that belong inside the compilerOptions field:

  • target: Enables the specification of the target JavaScript version that the compiler will output
  • module: Facilitates the utilization of a module manager in the compiled JavaScript code. CommonJS is supported and is a standard in Node.js
  • strict: Toggles strict type-checking protocols
  • esModuleInterop: Enables the compilation of ES6 modules to CommonJS modules
  • skipLibCheck: When set to true, bypasses the type checking of default library declaration files
  • forceConsistentCasingInFileNames: When set to true, enforces case-sensitive file naming

One crucial option you will need to enable is outDir, which determines the destination directory for the compiled output. Locate this option in the tsconfig.json file and uncomment it.

By default, the value of this option is set to the project’s root. Change it to dist, as shown below:

{
  "compilerOptions": {
    ...
    "outDir": "./dist"
    ...
  }}
Copy after login

While there are probably other configuration options you can add to the TypeScript compiler, the options above are basic specifications that can help you get started.

You should now update the main field in the package.json file to dist/index.js because the TypeScript code will compile from the src directory to dist.


The above is the detailed content of How to set up TypeScript with Node.js and Express. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:blog.logrocket.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template