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:
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:
Check out the GitHub repository for the source code; the main branch has the TypeScript project, and the JavaScript branch has the JavaScript version.
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
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:
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" }, ...}
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
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
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}`);});
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:
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.
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
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" }, ...}
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
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:
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:
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" ... }}
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!