DEV Community

Fonta22
Fonta22

Posted on

Importing libraries in TypeScript

If You're switching to TypeScript, like it happenned to me, you might don't know how to import properly libraries, so I hope this post would be useful πŸ˜ƒ.

Let's start, first of all we have to install the library that we want to use, in this case I'll be installing chalk. I'll do it with npm, so in the directory that we're gonna use it, we have to run this command on our terminal:

terminal:

npm i chalk
Enter fullscreen mode Exit fullscreen mode

Now that we have installed our library, let's see how import it on our TypeScript file (main.ts in my case).

There are many options to import a library in Ts, but I'll show you the most useful and simple ones in my opinion:

  • Import a single export:

main.ts:

import { blue } from 'chalk';

console.log(blue('Text')); // We use the function blue();
Enter fullscreen mode Exit fullscreen mode

In this case, we're just importing the function blue (used to color terminal text to blue). You can also give it the name you want:

  • Import a single export and giving it a name:

main.ts:

import { blue as colorBlue } from 'chalk';

console.log(colorBlue('Text'));
Enter fullscreen mode Exit fullscreen mode

You can also import more than one export at once, just like that:

main.ts:

import { blue, yellow } from 'chalk';

console.log(blue('Text'), yellow('More text'));
Enter fullscreen mode Exit fullscreen mode

And also name them:

main.ts:

import { blue as colorBlue, yellow as colorYellow } from 'chalk';

console.log(colorBlue('Text'), colorYellow('More text'));
Enter fullscreen mode Exit fullscreen mode

Now I'm going to explain the most useful import method in my opinion, which consists in import all the exports at once, and then you can use all of them that you want.

Also, in this case, it's compulsory to give it a name.

  • Import all exports at once:

main.ts:

import * as ch from 'chalk'; // You can give it the name that you want

console.log(ch.green('Text'), ch.purple('More text'));
Enter fullscreen mode Exit fullscreen mode

And that was all! I hope that this post were useful to you, if it was, give me a ❀, please! 😊

Top comments (0)