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.
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.
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");
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);
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.
→ 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
→ 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.
- 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
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"
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
→ 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
→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.
→ 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
→ So one approach isA place of node.Js's deceivedSyntax, let us useES6 Modulare SyntaxwasTypecript understands better.
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"},
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/
→ 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;
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 releasedapplicationuse((wrong:Mistake, req:enrollment, res:Responder, In order to,next:Next function) => {res.condition(500).JSON({Message: err.message});});applicationListen(3000);
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
→ 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) {}}
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;}}
→ 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) {}}
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});};
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;
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
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);
→ 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.
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
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});};
Level 3: broken
Let's connect the controller with routes.
src/rotas/all.ts
Router.receive('/',Gettodos);
Step 4: Post -Sem -execution application
→ By pressing the previous URL, we have successfully achieved all stored data.
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
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]});};
Level 3: broken
Let's connect the route update controller.
src/rotas/all.ts
Router.correction('/:I WOULD GO',Updatetetodos);
Step 4: Post -Sem -execution application
The update route is developed for the test in the postman
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
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"}
Level 3: broken
Let's connect the route update controller.
src/rotas/all.ts
Router.Remover('/:I WOULD GO',Deletetodos);
Step 4: Post -Sem -execution application
Let us carry out our exclusion route.
There is another package with which we configure the knot with the type, i.e. nest.js.it tries to explore it.
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.
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.