0
0
Typescriptprogramming~5 mins

Why modules are needed in TypeScript

Choose your learning style9 modes available
Introduction

Modules help organize code by splitting it into smaller parts. They keep code clean and avoid mixing everything together.

When your program grows and has many functions or classes.
When you want to reuse code in different files or projects.
When you want to keep variables and functions private to avoid conflicts.
When working with a team to separate work into parts.
When you want to load only the code you need for better performance.
Syntax
Typescript
export function greet() {
  console.log('Hello!');
}

import { greet } from './greetModule';
greet();

export makes code available outside the file.

import brings code from another file to use it.

Examples
Exporting a constant and importing it in another file.
Typescript
export const pi = 3.14;

import { pi } from './math';
console.log(pi);
Using export default to export a single main item from a module.
Typescript
export default function sayHi() {
  console.log('Hi!');
}

import sayHi from './sayHi';
sayHi();
Sample Program

This example shows how to export a function from one file and import it in another to use it.

Typescript
// file: mathUtils.ts
export function add(a: number, b: number): number {
  return a + b;
}

// file: app.ts
import { add } from './mathUtils';

const result = add(5, 3);
console.log('Sum is', result);
OutputSuccess
Important Notes

Modules help avoid naming conflicts by keeping code inside their own space.

Using modules makes your code easier to read and maintain.

TypeScript modules follow the same rules as ES6 JavaScript modules.

Summary

Modules split code into smaller, manageable parts.

They help share code between files safely.

Modules keep code organized and prevent conflicts.