Typescript is the current industry standard for creating JavaScript applications. It enhances our JavaScript code by adding types, enabling us to build large-scale products that are more maintainable and less error-prone.
In this article, we will discuss how to set up a TypeScript project for an Express app in a few simple steps.
Prerequisites
- You should have Node.js installed on your machine.
- You should also have a basic knowledge of Node.js and Express.
Create a new folder for your project and initialize a package.json file
mkdir typescript-express-server
cd typescript-express-server
npm init -y
The npm init -y prompt creates a new package.json file with the following content:
{
"name": "article",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
...
}
Install TypeScript
There are two ways to do this:
Globally
If you install TypeScript globally, you don't have to reinstall it for every project. To install TypeScript globally, run the following command:
npm i -g typescript
Locally
You can also install TypeScript locally for only the current project using the following command:
npm i -D typescript
Install other dependencies
npm i express; npm i -D ts-node @types/express
The -D flag indicates that we're going to need ts-node and @types/express only in development mode. We'll use ts-node to compile and run our TypeScript code.
Generate the ts.config file
If you installed TypeScript globally, generate the tsconfig.json file with the following command:
tsc --init
If you installed it locally, use the following command instead:
npx tsc --init
The ts.config serves as the configuration file for the TypeScript compiler. You can modify this file to customize the compiler settings for your project. It comes with a lot of commented-out options. Comment out and edit the following options:
{
"compilerOptions": {
....
"module": "NodeNext",
"rootDir": "./src",
"moduleResolution": "NodeNext",
"outDir": "./dist",
....
}
}
In the tsconfig.json file above, the settings:
-
"rootDir": "./src"specifies that the TypeScript compiler will look for source files in the./srcdirectory. -
"outDir": "./dist"specifies that the compiled JavaScript files will be output in the./distdirectory. Later, we'll set up annpm run buildcommand in ourpackage.jsonthat will trigger the compilation process, using these settings to transform our TypeScript code into JavaScript files in the./distdirectory.
File structure
Currently, here's a recommended file structure for your project, omitting the node_modules directory:
├── .env
├── .gitignore
├── package-lock.json
├── package.json
├── src
│ └── index.ts
└── tsconfig.json
Update package.json file
{
"name": "article",
"version": "1.0.0",
"main": "dist/index.js",
"type": "module",
"scripts": {
"dev": "node --loader=ts-node/esm --env-file=.env --watch src/index.ts",
"build": "tsc",
"start": "node dist/index.js"
},
...
}
Here's a summary of the changes made in the package.json file:
-
Main Entry Point: Updated
"main": "dist/index.js"to point to the compiled JavaScript file. -
Module Type: Changed
"type": "module"to enable ES6 imports and exports. -
Scripts:
-
“dev”: Runs the development server withnodeand:-
—-loader=ts-node/esmfor compiling and running TypeScript code. -
--env-file=.envto load environment variables from the.envfile. -
--watchto reload code after every change. -
src/index.tsas the entry point.
-
-
“build”: Compiles TypeScript code to JavaScript and outputs it to the./distfolder usingtsc(change tonpx tscif you installed TypeScript locally on the current project). -
“start”: Starts the server in production mode.
-
Create a basic server
In your src/index.ts file, write the following lines of code:
import express, { urlencoded, json } from "express";
const port = process.env.PORT || 8000;
const app = express();
app.use(urlencoded({ extended: true }));
app.use(json());
app.get("/", (req, res) => {
res.status(200).json({ msg: "Server is up and running" });
});
app.listen(port, () => {
console.log(`Server is listening at port ${port}`);
});
In your .env file, write the following line:
PORT=3000
Running the program
npm run dev
If everything is working fine you should see Server is listening at port 3000 on your terminal.
Verify your app
Now that your application is running, you can verify that it's working by accessing the URL: http://localhost:3000/.
You can use:
- Your web browser to open the URL and see the app in action
- Extensions like Thunder Client or Postman to test the API endpoints
Conclusion
This article has guided you through setting up a TypeScript project with Node.js and Express.js, minimizing unnecessary package installations. You've learned to create a efficient development workflow, leveraging TypeScript's benefits while keeping your project lightweight.
I hope you found this tutorial helpful in getting started with TypeScript and Express.js. Happy coding!
Top comments (0)