This content originally appeared on DEV Community and was authored by Garima
So, I’m pretty new to TypeScript. As someone who’s been working with Node.js and JavaScript for a while, I thought switching to TypeScript would be a breeze. You know, it's just JavaScript with types slapped on, right? Well, I quickly realized it’s not that simple.
I wanted to find a good guide or video that explained how to build a Node.js server with TypeScript from scratch—something that didn’t feel like a puzzle missing half the pieces. But honestly, most of the stuff out there either skimmed over the basics or assumed I was already some TypeScript expert. It was frustrating!
That’s when I thought, why not write down everything I’ve learned so far? If you’re a JavaScript or Node.js developer like me, and you’re struggling to find a decent step-by-step on how to get started with TypeScript, I’ve got you covered. Let’s make this transition as smooth as possible, without the head-scratching moments.
Alright, let’s dive in! We will set up a Node.js server with TypeScript, and we will look at some other cool tricks along the way.
Step 1: Initialize Your Node Project
First things first, we need to initialize a Node.js project. Open up your terminal, go to your project folder, and run this command:
npm init -y
The -y
flag just skips all the annoying setup questions like package name, version, etc. It says "yes" to everything, and bam! You’ve got yourself a package.json
file. This is where Node.js tracks all the dependencies and scripts for your project.
Step 2: Create Your First File
Next up, create a file named index.js
. For now, we’ll work in plain JavaScript to see how things work before we switch to TypeScript.
In index.js
, let’s try importing a package. The traditional way of doing this in Node.js is by using CommonJS syntax:
const fs = require('fs');
Here, we are using the built-in file system module, a common pattern in Node.js. If you’ve worked with JavaScript before, this should be familiar. However, most developers today prefer using the import-export syntax as it looks cleaner, more organized, and fancy.
Now if we convert this to the new syntax
import fs from 'fs';
Now of we try to run this code we might be getting some errors stating some warning saying we cannot use this ES module unless we update our package.json and change the type to module
Simply add type: 'module'
in the package.json
file. This tells Node to use Es module instead of require. And now our code might be working fine.
type: 'module'
Now, let's talk about Typescript because this is what this blog is all about. Go ahead and install typescript
as a dev dependency because we don't need it in the production environment. You can use any package manager you want to use for installing the packages whether it be pnpm
, bun
, npm
or whatever.
npm i typescript --save-dev
Yeah, we have installed it but what exactly is typescript?
TypeScript is a superset of JavaScript, meaning it is built on top of JavaScript by adding optional static typing. This means you can define the types of variables, functions, and objects, helping to catch errors early in the development process.
Now this is important! TypeScript code needs to be compiled into regular JavaScript so that it can run in browsers or Node.js environments, as they don't natively understand TypeScript. And now we know why we don't need it in the production environment.
To convert the Typescript code to Javascript, we need to add a script in out package.json
that will run the Typescript compiler that converts the TS code to the JS or technically speaking building the application. Go to the package.json
and inside the scripts object add a build command that helps us to do the covering thing.
scripts: {
build: "tsc".
// ... rest of the commands
}
Typescript needs some configurations to get started with it. Before actually starting the configuration let's organise out root directory. Create a src
folder and drag the index.js
file we just created and change the extension to .ts
now we have an index.ts
file inside the src
folder.
When using node built-in modules you might get an error that says it cannot find corresponding type declarations. In lay man, it says install the types for node. Install the types for node using this command and the error should disappear.
npm i @types/node --save-dev
As soon as you install Typescript in the above step, you might be able to see a tsconfig.json
file if not go ahead and create it, we don't have to worry about it. We will now configure typescript to make it behave like we want it to.
{
"compilerOptions": {
"target": "es2020",
"module": "NodeNext",
"rootDir": "./", // Update this to your source directory
"outDir": "./dist" // Update this to your desired output directory
},
"include": ["./" ], // Ensure this matches your source directory
"exclude": [ "node_modules", "dist"] // Exclude output and dependency directories
}
You can copy-paste the configurations above or create your own to, but trust me this config works for almost all of the TS projects.
target
: Specifies the JavaScript version that TypeScript should compile to. "es2020" here means the compiled code will use ECMAScript 2020 features.
module
: Determines the module code generation method. "NodeNext" is suited for modern Node.js environments that use ES Modules (import/export syntax) rather than CommonJS.
rootDir
: Specifies the directory where your source code files are located. "./" means the root directory, but you can change it to your specific source folder.
outDir
: Defines where the compiled JavaScript files will be output. "./dist" sets this to the dist folder, so all compiled files go there.
include
: Specifies which files and folders to include in the compilation. "./" includes all files in the root directory. Adjust it if your source files are in a different folder.
exclude
: Excludes certain directories from compilation, typically those you don’t want TypeScript to process. Here, "node_modules" (dependencies) and "dist" (output folder) are excluded to avoid redundant checks.
Go into the terminal and run the build command we just wrote in package.json
npm run build
Now, you might be able to a dist
folder in your root directory containing an index.js
file. This command generates the dist folder that contains the Javascript code that we can actually run on NodeJs.
Yolla! We are done with creating our Nodejs server using Typescript. There are tons of other options to configure the tsconfig but I don't think we would need to use them.
Now the question is do we need Typescript?
Whether or not, it totally depends on one's project's needs. But, I believe using Typescript makes Javascript somewhat strict. It provides type-checking and various other features. As Javascript is a dynamically typed language, it can do blunders sometimes, you may never know what is leading to the server crash. Where you might be accidentally updating a string var with an integer. Javascript is sweet it will allow you to do that, but Typescript no,no sweetheart!
In the end, it's all Javascript :)
Want to connect?
twitter · blogs · portfolio · email · linkedin
Written and edited by me❤️
This content originally appeared on DEV Community and was authored by Garima
Garima | Sciencx (2024-10-29T03:44:30+00:00) Step by Step guide to setup Node server with Typescript. Retrieved from https://www.scien.cx/2024/10/29/step-by-step-guide-to-setup-node-server-with-typescript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.