loading...

Minimal ts-node starter

ziishaned profile image Zeeshan Ahmd ・2 min read

My goal is by creating this small minimal ts-node starter is to kickstart small applications for simulating small tasks.

I mostly prefer doing small tasks outside the application as it helps me to clearly understand the implementation of the task and also the end result contains fewer bugs. Without further ado, let's start by creating a new directory by running the following command:

mkdir ts-node-starter

Now open ts-node-starter directory inside your terminal and initialize package.json by running following command:

yarn init -y

The above command will create a new file called package.json. Now let's install some dependencies which will help us running typescript files in Node.js. For that you have to run the below command:

yarn add ts-node typescript

Now let's create a new typescript file and name it index.ts and put the following content inside of it:

const message: string = "Hello, World!";
console.log(message);

After doing the above process open the terminal and run the following command:

./node_modules/.bin/ts-node index.ts

You will see the following output in your terminal:

Hello, World!

Until now what we can do our job but we want to automate that. For that let's create a new script in the package.json file.

"scripts": {
  "dev": "./node_modules/.bin/ts-node index.ts"
}

Now after update the scripts key in package.json run the below command:

yarn run dev

The above command will out following inside the terminal:

Hello, World!

But the only problem is left is when we change anything in our code we have to again run yarn run dev command to execute the code. We can also automate that by installing nodemon. nodemon is used to run a specific command when upon file changes. Now lets open package.json file and update our dev script.

"scripts": {
  "dev": "./node_modules/.bin/nodemon --exec ./node_modules/.bin/ts-node index.ts"
}

Now let's open your terminal again and rerun yarn dev command. At this time you will see the Hello, World output but the command will not exit the process as now we are watching for the file changes using nodemon. Now open index.ts file and change message variable value to Hello, John. After changing the variable value you will see Hello, John printed inside the terminal.

Helpful tools

Install missing TypeScript typings for dependencies in your package.json.

Upgrades your package.json dependencies to the latest versions.

You will be able to find the above code on GitHub.

Posted on by:

ziishaned profile

Zeeshan Ahmd

@ziishaned

Full-stack web developer and open source lover

Discussion

markdown guide