Node.js and express.js with type script (2023)

Node.js and express.js with type script (1)

JavaScript on the server side has recently become very popular and is mainly used withNode.js o express.js con javascript.

The development ofNode.jsMarks JavaScript asTechnology on the emerging server side.

Node.jsIt is an open environment with a multi -platform -Javascript execution time in which the JavaScript code is carried out outside of a web browser.

Node.js and express.js with type script (2)

TyposcriptIt is an open source language based on JavaScript, tools and adds static definitions. It has many additional resource and execution time controls that are used in many projects.

Node.js and express.js with type script (3)

Let us understand how we can simply use the knot with type script.

At the end of this blog we will know how to write TypeScript with node.js and express.js

Basic familiarity of node.js and express.js

NPM installation -g NPM // node installation
NPM Install Typescript-Save DEV // TypeScript Installation

→ we create a new project directory and create aApp.tsArchive and write a code on the side.

src/app.ts

Console.log ("something went wrong");
Node.js and express.js with type script (4)

To perform the script node.js, we write

nodo app.ts

On the previous screen, see the console successfully on the terminal.

F. Is the JS node compatible with TypeScript?

Let us check by writing the basic entered code on the same page

src/app.ts

Varized Var: number;Alter = 25;Console.Start session(Year old);
Node.js and express.js with type script (5)

Nó LanzaA mistakenoTerminalOn the previous screen it is clear that this is clearNode.jsesIt is not directly compatible with TypeScript.

Let us carry out the type script by executing the following command.

Tsc App.ts

An app.js.

Node.js and express.js with type script (6)

→ The JavaScript file is well executed.

→ This is really important to understandThe type script does not perform the knot.

→ There is aPackageThis will help to carry out the node with type script in the background

→ That willCombine the TSC and the knot in a single step

Packagenodos ts

Package: https://www.npmjs.com/package/ts-nodo

Github: https://github.com/TypeStrong/ts-nodo

Node.js and express.js with type script (7)

→ thatPackageIt may beGood in development, Then whatFor the productionTo really use your file on the web server in this wayIt's not idealWhy did it?Additional compilation stepEvery time the code is carried outAdd toThis will do thatCost optimization.

→  Here we see the configuration of the node expressionTyposcriptCompiler andOger without js.

  1. Atmosphere Do Nó:

Open the project at the terminal and carry out the following commands.

NPM Init --- Yes // Create the package file
NPM Install Express Body-Parser Nodemon // Packages
Node.js and express.js with type script (8)

2. Entered the environment:

TSC -init.// Create the file tsconfig.ts file

tsconfig.jsonand theHerzthe typed file

We have to make the following settings:

{"Compileroptions": {{"Goal": "ES2018","Moses": "CommonJs""Moduleresolution": "Nodo","Outrir": "./Dist",/ * JS files here live */"Rootdir": "./src",/ * The TS file is here *//......}

Moduleresolution: "Nodo"

(Video) How to Setup Node.js with TypeScript in 2023

By default when we runTsc Domain, Your compiled JS file is created in the same place. The standard practice is to have TS and JS codes in the separate directory

MY.

SRC: It will contain all TS codes.

Dist - it will contain the JS code

Node.js and express.js with type script (9)

 → The TypeScript code is written in the SRC directory and after the compilation the JS code is generated inKreisDirectory.

 → we now create the first node code on TypeScript:

Src/app.ts (Archivo root)

const express =requirement('Fast');App apt =Fast();applicationListen(3000);// Puerto
Node.js and express.js with type script (10)

Package.jsonIt is the heart of the file node.j to deal with packages.

→ After writing the node.js codes, the type script starts when it comes to execution errorTSC -WDomain. Note the screen recording.

→ This is becauserequirementIt is used inAtmosphere Do Nó Export Import.FOR TypeScript must installDefinitely written package.

Definitely parcel typesIt is a defined tipycript package. The code that works at Vanilla JS also works here. We have to install two packages:

NPM Install @Types/NóNpm install @tipos/express

If you want to learn more about @types on TypeScript, you can visithere.

After installation,requirementThe error is gone.

Node.js and express.js with type script (11)

→ a point must be taken into account whenDisadvantage in the application variables, his derived type syntax is:NoneThis will do thatnot better understoodDutch type for Express.js

Node.js and express.js with type script (12)

→ So one approach isA place of node.Js's deceivedSyntax, let us useES6 Modulare SyntaxwasTypecript understands better.

Node.js and express.js with type script (13)

nowapplicationINFECS -Variable: ExpressarLike the guy who works smoothly with the knot and that

TRICK:Use the node and the typical common approach ES6 for code division and modularization.

Package.jsonFile, we addNodemon GuiónNodemon is used to start the node server that you do not need, and the server restarts in every code change.

"Scripts": {"Top": "Dedemon dist / App.js"},
Node.js and express.js with type script (14)

To start the server:

TSC - -Watch // This starts the typical text compiler
NPM Start // This starts the Knot server

Let us run the URL in the browserhttp://localhost:3000/

Node.js and express.js with type script (15)

→ In this application we will do thisCreate all applicationnoNode.js, express.js y TypeScript.

→ We have already installed the previous Express package. I hope this app is fun.

→ Let us use AThe pictureProData storage(Not the database). The idea is that we will write TypeScript with node.js.connect databases that can be complicated today.

Let's start with the development.

Step 1: Creation of terminal routes.We will write the logic of the routes under the creation of controllers.

Create new directory routes as followed by the all. This is the route file.

src/rotas/all.ts

Import {Router} vpn 'Express';// Way Node alt// const express = required ('express');// const router = express.router;Const router =Router();Router.Post('/');Router.receive('/');Router.correction('/:I WOULD GO');Router.Remover('/:I WOULD GO');Export predetermined exporterers;
Node.js and express.js with type script (16)

Note: The Route Controller is not added today, we will do it soon.

Step 2: Connection routes/All.TS with App.TS

src/app.ts

Importar Express, {application, answer, nextFunction} de 'Express';Import './routte/ all'; // connected routeApp apt =Fast();applicationuse('/All', out);// This means that the entire route is preceding the route of this route
// The following route is activated when an error is released
applicationuse((wrong:Mistake, req:enrollment, res:Responder, In order to,next:Next function) => {res.condition(500).JSON({Message: err.message});});applicationListen(3000);
Node.js and express.js with type script (17)
(Video) How To Use TypeScript With Express & Node

Level 3: Controller

→ Here we will write themThe commercial logic of the routes, ie how should this route do?We have created a new directory that refers to the routes

→ Step by step we create a route controller

SRC/Controller/All.ts

Import {RequestHandler} von 'Express';Export ConstanteCreatetodos:RequestShandler= (Req, res,,next) => {};

Note: The application is a quick alternative to

((wrong:Mistake, req:enrollment, res:Responder, In order to,next:Next function)This is definitely written

Node.js and express.js with type script (18)

→ elcoreologicalwill besimple, I haveA matrix whose data decide the list of outstanding tasks.

→ We believe in an empty matrix (say everything)

→ of type script, we knowAll classes can be used as typesnovariables. So we created thatBlop of the array (ie variable: class).The plane will be on models

It will be a basic class that accepts the identification and text of the type chain.

Src/models/todos.ts

Export classEverything{Constructor (by Público: String, Public Text: String) {}}
Node.js and express.js with type script (19)

We use a shorter syntax method, with identification and text with the same name instantiated and attributed.

Alternative form (regular form):

Export classEverything{ID: chain;Text: chain;Constructor (from: String, text: string) {this.id = id;this.text = text;}}
Node.js and express.js with type script (20)

→ We will create the handlingFour routesLogik: CRUD -Operation, dh Createph

Rota1: rota createtodos

Routen name: Createtodos

Application type: publication,

Rules:Createtodos

This route is aPOSTRequest where we will deal with ourselvesInsert operation.

Level 1: Model

Src/models/todos.ts

That isTogether for the four routes. He says to everything that the matrix data in {id: __, text: __} format will have.

Export classEverything{Constructor (by Público: String, Public Text: String) {}}
Node.js and express.js with type script (21)

Level 2: Controller

SRC/Controller/All.ts

In this controllerTextIs fromNavigator/postmanyI WOULD GOesexclusivelygenerated.

Import {Requesthandler, Answer} from 'Express';Import {all} of '../models/todos';Everything constant:Everything[] = [];Export ConstanteCreatetodos:RequestShandler= (Req, res,,next) => {const text = (req.body como {text: string}) .text;// Make the type of electricity// const text = req.body.text; // datilldescript does not allow: any typeConsta id = mathematics.Coincidentally().prison();Const newtodo = neuEverything(ID, Text);ALL.To press(Newtodo);res.condition(201).JSON({Message: 'Everything that was created successfully', Createtodo: Newtodo});};
Node.js and express.js with type script (22)

CreatetodosIt is a typing functionRequestShandlerTwo application cards are received:

A text- This is received from the application (in the JSON format). This is the text of the homework

B. identification- Exclusive data. This can be done in many ways. For this project we will use the basicsMath.random ()Integrated JavaScript function.

→ The next step is to connect this controller to the route.

Level 3: broken

Let's connect the controller with routes.

SRC/Runds.Tod.Ts

Import {Router} vpn 'Express';Import {createtodos} of '../Controllers/todos';Router.Post('/',Createtodos); // Create routeExport predetermined exporterers;
Node.js and express.js with type script (23)

Step 4: JSON recording application:

→ The last phase of the route isRegister from JSONnoApp.tsYou can therefore receive JSON inquiries from the browser/postman.

→ This happens once for all routes.

src/app.ts

(Video) Learn Express JS With TypeScript

Importar Express, {application, answer, nextFunction} de 'Express';......App apt =Fast();applicationuse(JSON());// Register this middleware to accept JSON inquiriesapplicationuse('/All', toDoroutes);// The entire route must be continued with this path
...
applicationListen(3000);
Node.js and express.js with type script (24)

→ All routes begin with <The Path>/All/<tge_Name> (written in line 8 above the screen recording).

→ How this route isPostal application, we will usePostman.Postman has skills to accept all kinds of inquiries: publish, maintain, patch, maintain

Step 5: Post -Sem -execution application

→ By pressing the previous URL, we successfully save the data.

Node.js and express.js with type script (25)

Data for postman:

URL:http://localhost:3000/all/Body:{
"Text": "Technological Meetupps" // To save your data from everything
}
// type of gross body in JSON format

→ The development of creation is carried out.

ROTA 2: ROTA GETTIDES

Routen name: Gettodos

Application type: preserved,

Rules:Gettodos

This route is aRECEIVERequest where we will deal with ourselvesReading processWe created the controller for this route.

Level 1: Models

This is the same as the previous one

Node.js and express.js with type script (26)

Level 2: Controller
SRC/Driver/Rota.ts

Get the controller Willhand backAllDicekept in itThe entire matrix.

Export ConstanteGettodos:RequestShandler= (Req, res,,next) => {res.condition(200).JSON({"everyting everything});};
Node.js and express.js with type script (27)

Level 3: broken

Let's connect the controller with routes.

src/rotas/all.ts

Router.receive('/',Gettodos);
Node.js and express.js with type script (28)

Step 4: Post -Sem -execution application

→ By pressing the previous URL, we have successfully achieved all stored data.

Node.js and express.js with type script (29)

Rota 3: Rota de Updatetodos

Routen name: update modos

Application type: patch, patch,

Rules:Updatetetodos

This route is aCORRECTIONRequest where we will deal with ourselvesUpdate processesFor this request, we have to pass the exclusive identification that the route is preserved from the update.

We believe that the controller for this route.

Level 1: Models

This is the same as the previous one

Node.js and express.js with type script (30)

Level 2: Controller

SRC/Controller/All.ts

In Postman we approved identification whose data must be updated. We getI WOULD GOsinceURLyNew text for updatingsinceapplication.

Export ConstanteUpdatetetodos:RequestShandler<{id: string}> = (req, res,next) => {const todoid = req.params.id;Constant updated = (req.body as {text: string}). Text;It consists of all = everyone.FindIndex(x => x.id === todoid);if (todoIndex <0) {LitterMistake('I couldn't find everything!');}Alle [da Benx] = NeoEverything(Todos [todoIndex] .Id, UpdateETETEXT);res.condition(201).JSON({Message: 'everything updated correctly', everything updated: all [all indices]});};
Node.js and express.js with type script (31)
(Video) Node.js API From Scratch Using TypeScript, Express And MongoDB #1

Level 3: broken

Let's connect the route update controller.

src/rotas/all.ts

Router.correction('/:I WOULD GO',Updatetetodos);
Node.js and express.js with type script (32)

Step 4: Post -Sem -execution application

The update route is developed for the test in the postman

Node.js and express.js with type script (33)
Node.js and express.js with type script (34)
Node.js and express.js with type script (35)

Route 4: Delete all route

Routen name: Deltetodos

Application type: delete,

Rules:Deletetodos

The elimination of the process is similar to the update request with some differences.

Level 1: Models

This is the same as the previous one

Node.js and express.js with type script (36)

Level 2: Controller

Eliminate the controllerFind the previous identification and check the entire matrix.
SRC/Controller/All.ts

Export ConstanteDeletetodos:RequestShandler<{id: string}> = (req, res,next) => {const todoid = req.params.id;It consists of all = everyone.FindIndex(x => x.id === todoid);if (todoIndex <0) {LitterMistake('I couldn't find everything!');}Console.Start session(Todos [todoIndex] .Text, typeof tdoIndex);const deletedData = {id: todos [todoIndex] .id, texto: Todos [todoIndex] .Text};
ALL.modification(TodoIndex, 1);
res.condition(201).JSON"}
Node.js and express.js with type script (37)

Level 3: broken

Let's connect the route update controller.

src/rotas/all.ts

Router.Remover('/:I WOULD GO',Deletetodos);
Node.js and express.js with type script (38)

Step 4: Post -Sem -execution application

Let us carry out our exclusion route.

Node.js and express.js with type script (39)

There is another package with which we configure the knot with the type, i.e. nest.js.it tries to explore it.

Node.js and express.js with type script (40)

We learned two important concepts:

A. letter from node.js and express.js with typecript.

B. JS JS packages of vanilla of third -party providers in Typescript, ie, @Typepes/node, @Typepes/Express.

Github:

Node.js and type script are so powerful.

(Video) TypeScript Setup With Node & Express

I hope you learned something new today.

Thank you for being 🙌 to the end.AiTo see other tips, articles and things that I learn and share there.

Videos

1. How to Setup TypeScript in Node js and Express Server
(The Brave Coders)
2. Build a RESTful API with Node.js, Express & TypeScript
(TomDoesTech)
3. How to Setup a Node Express API with TypeScript
(ProgrammingKnowledge)
4. How to setup Nodejs Express with Typescript
(Mafia Codes)
5. Using Typescript in Node.js
(Ben Awad)
6. TypeScript With Node And Express | Node And Express Explained | TypeScript Tutorial | Simplilearn
(Simplilearn)

References

Top Articles
Latest Posts
Article information

Author: Maia Crooks Jr

Last Updated: 10/11/2023

Views: 5495

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Maia Crooks Jr

Birthday: 1997-09-21

Address: 93119 Joseph Street, Peggyfurt, NC 11582

Phone: +2983088926881

Job: Principal Design Liaison

Hobby: Web surfing, Skiing, role-playing games, Sketching, Polo, Sewing, Genealogy

Introduction: My name is Maia Crooks Jr, I am a homely, joyous, shiny, successful, hilarious, thoughtful, joyous person who loves writing and wants to share my knowledge and understanding with you.