0
0
Typescriptprogramming~5 mins

Re-exporting modules in Typescript

Choose your learning style9 modes available
Introduction

Re-exporting modules lets you gather exports from different files and share them from one place. This makes your code easier to organize and use.

You want to create a single file that collects and shares many exports from different files.
You want to simplify imports in other parts of your app by importing from one file instead of many.
You want to hide the internal structure of your modules and only expose what matters.
You want to rename or filter exports before sharing them.
You want to keep your code clean and easier to maintain.
Syntax
Typescript
export * from './module';

export { name1, name2 } from './module';

export { originalName as newName } from './module';

export * from './module'; shares everything exported by module.

You can pick specific exports or rename them when re-exporting.

Examples
This shares all exports from mathUtils module.
Typescript
export * from './mathUtils';
This shares only add and subtract functions from mathUtils.
Typescript
export { add, subtract } from './mathUtils';
This shares add function but renames it to sum when exporting.
Typescript
export { add as sum } from './mathUtils';
Sample Program

We have two modules: mathUtils and stringUtils. The index.ts file re-exports all math functions and the shout function from stringUtils. In main.ts, we import everything from index.ts and use the functions.

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

export function subtract(a: number, b: number) {
  return a - b;
}

// file: stringUtils.ts
export function shout(text: string) {
  return text.toUpperCase() + '!';
}

// file: index.ts
export * from './mathUtils';
export { shout } from './stringUtils';

// file: main.ts
import { add, subtract, shout } from './index';

console.log(add(5, 3));
console.log(subtract(10, 4));
console.log(shout('hello'));
OutputSuccess
Important Notes

Re-exporting does not create new copies of the exports; it just forwards them.

Be careful to avoid circular dependencies when re-exporting modules.

You can combine re-exporting with local exports in the same file.

Summary

Re-exporting helps organize and simplify your imports by sharing exports from one place.

You can export everything, some parts, or rename exports when re-exporting.

This keeps your code cleaner and easier to maintain.