In this article, we will find something out about creating typescript project in Node.js. It makes us actively demo small project when working with Angular, React.js, …
Let’s get started.
Table of contents
Creating a typescript project in Node.js
-
Initialize node.js project
We will create our own project with
npm init -y -
Install some necessary packages
-
Use
typescriptpackagenpm install --save-dev typescriptNode.js is an engine that runs Javascript and not Typescript. The node Typescript package allows us to transpile our .ts file to .js scripts.
Inside our package.json, we will put a script called tsc:
"script": { "tsc": "tsc" }This modification allows us to call typescript functions from the command line in the project’s folder. So, we can use the following command:
npm run tsc -- --initThis command initializes the typescript project by creating the
tsconfig.jsonfile. Within this file, we will uncomment theoutDiroption and choose a location for the transpiled.jsfiles to be delivered. -
Use
@types/nodepackageSo,
@types/nodepackage is an type declaration package for Node.js, it has the same name as the package on npm, but prefixed with @types/, but if we need, we can check out https://aka.ms/types to find the package for our favorite library.npm install --save-dev @types/node
-
-
Scripts for
package.jsonfile"scripts": { "tsc": "tsc", "prod": "tsc && node ./build/index.js", "build": "tsc" } -
Debugging in typescript project with Node.js
-
Contents of
tsconfig.jsonfile{ "compilerOptions": { "target": "es5", "module": "commonjs", "outDir": "./build", "sourceMap": true } } -
Contents of
lauch.jsonfile{ "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch Program", "program": "${workspaceFolder}/src/index.ts", "preLaunchTask": "tsc: build - tsconfig.json", "outFiles": ["${workspaceFolder}/build/**/*.js"] } ] } -
If we encounter some errors such as
"preLaunchTask": "tsc: build - tsconfig.json"or... is not recognized as an internal or external command, operable program or batch file. The terminal process terminated with exit code: 1We can fix this problem with the solution that is to createan npm script that run tsc, and then run that script in the vs code launch.json.
In
package.jsonfile, we have:"script": { "debug": "tsc --sourcemap" }In
.vscode/launch.jsonfile, we have:{ "type": "node", "request": "launch", "name": "Debugger", "program": "${workspaceFolder}/src/index.ts", "preLaunchTask": "npm: debug", "outFiles": [ "${workspaceFolder}/build/*.js" ] }
-
Wrapping up
- Understanding about task in vs code.
Thanks for your reading.
Refer: