Modules
Import Styles
- Import Entire Module as an Object
import * as MathUtils from "./mathUtils";
console.log(MathUtils.add(2, 3)); // 5
- Import Side Effects Only
// setup.ts
console.log("Setup done!");
// main.ts
import "./setup"; // runs the file but imports nothing
Namespaces vs. Modules
- Namespaces (old way): Used inside one file/project to organize code in a global scope.
- Modules (modern way): Each file is a module. Import/export is used between files.
Namespaces
- A namespace in TypeScript is a way to group related code (variables, functions, classes, interfaces) under a single logical name.
- Prevents naming conflicts in large projects.
- Similar to “packages” in Java or “namespaces” in C#.
Before ES6 import/export, namespaces were the main way to organize TypeScript code.
namespace MathOperations {
export function add(a: number, b: number): number {
return a + b;
}
export function subtract(a: number, b: number): number {
return a - b;
}
}
exportkeyword → makes items accessible outside the namespace.- Without
export, items remain private inside the namespace.
In TypeScript, you don’t "import" namespaces in the same way you do with ES6 modules. Instead, you can refer to the exported elements directly after the namespace, assuming they are globally available.
console.log(MathUtilities.add(3, 4)); // 7
console.log(MathUtilities.multiply(3, 4)); // 12
Alternatively, if the namespace is exported from another file, you would include the appropriate reference.
Namespaces are mostly used in older TypeScript projects or when not using module systems like ES6/CommonJS.
- Can be nested for hierarchy.
- Can be split across files using
/// <reference path="..." />.
Re-export
- Re-exporting means taking something exported from one module and exporting it again from another module.
- It’s often used to create a “barrel file” (a single entry point that re-exports everything from multiple modules).
- This makes imports cleaner and more maintainable.
export * from "./module";
Re-exporting Default Exports
export { default as Car } from './car'; // Re-exporting default export as named
Re-exporting in Namespaces
namespace AllMath {
export { MathOperations }; // Re-exporting the entire MathOperations namespace
export { MoreMath }; // Re-exporting the entire MoreMath namespace
export { AnotherMath.multiply };
}