1/29/20

Node Express in Typescript


TypeScript is an open-source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript and adds optional static typing to the language. TypeScript is designed for the development of large applications and transcompiles to JavaScript.

this is a node typescript sample project, you can check out it.
https://github.com/najathi/node-ts-basic
After the clone the files you need to install the npm package manager.

Basic setup in node using typescript
install the typescript
npm i -g typescript

check typescript version
tsc --version

create app.ts file
windows cmd:
echo some-text  > app.ts

linux / max cmd:
touch app.ts

open the file in VSCode:
code app.ts

compile the file cmd: (it generate a javascript file)
tsc app.ts

constantly watch the file
tsc app.ts -w

you want to generate the config file (tsconfig.json):
tsc --init

tsconfig file configurations
-------------------------------------
target - ecmascript version (you can select ES5 / ES6, I selected ES6)
module -  common js
outDir - compile javascript to go (eg: "./dist")
rootDir - typescript files are stored (eg: "./src")
moduleResolution - node

note: app.ts has to move to the "src" folder.

After creating the tsconfig.json file, run the command: (That makes dist-> app.js (compiled))
tsc


how to setup the project node in typescript??

npm initialize:
npm init -y

install express js:
npm i express

we have to install certain packages (devDependencies)
- typescript
- ts-node
- nodemon
- @types/node - checking the types
- @types/express -  checking the types

npm i -D typescript ts-node nodemon @types/node @types/express


add scripts in package.json:
"scripts": {
    "start": "node dist/app.js",
    "dev": "node src/app.ts",
    "build": "tsc -p ."
  }

generate compile typescript into dist folder command:
tsc -p .

npm start - just run dist/app.js file
npm run dev - run and watch the src/app.ts file
npm run build - compile all ts file into js file

No comments:

Post a Comment

About

Hi, I'm Najathi.
I've started entrepreneurial company, Twin Brothers.Inc.
One is self-funded & the other is venture backed. I also send a weekly. where I share relevent, curated links.

Every Week I Publish a short post on writing, publishing, or content of IT Related

Contact Form

Name

Email *

Message *