Step 12 – Introduction to Modules in TypeScript

In TypeScript, modules are used to organize code into reusable pieces of code that can be imported and used in other parts of the application. Modules allow developers to keep their code organized, make it more reusable, and easier to maintain.

A module can be a single file, or it can be a collection of files that are organized together. Each module can have its own dependencies, and it can export variables, functions, classes, and other constructs that can be used in other parts of the application.

Creating a Module in TypeScript

To create a module in TypeScript, we need to use the export keyword to make the variables, functions, classes, and other constructs available to other parts of the application. Here’s an example:

// greeting.ts
export function sayHello(name: string) {
  console.log(`Hello, ${name}!`);
}

In this example, we define a function called sayHello and export it using the export keyword. This makes the sayHello function available to other parts of the application that import this module.

Importing a Module in TypeScript

To use a module in TypeScript, we need to import it using the import keyword. Here’s an example:

// main.ts
import { sayHello } from "./greeting";

sayHello("John");

In this example, we import the sayHello function from the greeting module and use it in the main module.

Default Exports in TypeScript Modules

In addition to named exports, TypeScript also supports default exports. A default export is a single construct that is exported from a module, and it can be imported without using braces. Here’s an example:

// greeting.ts
export default function sayHello(name: string) {
  console.log(`Hello, ${name}!`);
}

In this example, we define a function called sayHello and export it as the default export using the export default syntax.

To import a default export, we can use any name we want. Here’s an example:

// main.ts
import myGreeting from "./greeting";

myGreeting("John");

In this example, we import the default export from the greeting module and call it myGreeting.

Conclusion

Modules are a powerful feature of TypeScript that allow developers to organize their code into reusable pieces of code that can be imported and used in other parts of the application. By using modules, we can keep our code organized, make it more reusable, and easier to maintain.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.