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.
Re-exporting modules in 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.
mathUtils module.export * from './mathUtils';
add and subtract functions from mathUtils.export { add, subtract } from './mathUtils';
add function but renames it to sum when exporting.export { add as sum } from './mathUtils';
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.
// 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'));
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.
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.