In TypeScript, modules provide a way to organize code into reusable and encapsulated units.
Modules help in structuring code, avoiding naming conflicts and promoting code organization and maintainability.
Modules allow us to split one large file code into separate files, making it easier to manage, maintain, and reuse across different parts of our application or even across multiple projects.
Modules help in achieving a more modular and scalable codebase by providing a clear structure for organizing code and managing dependencies.
There are two main ways to work with modules in TypeScript: using the import and export statements or leveraging the ES6 module syntax.
use the `import` keyword when needs to inherit source code from another file.
import { variableName, className, interfaceName, methodName } from './file-path';
export const variableName: string = "Message"; export function functionName(): void {} export class ClassName {} export interface InterfaceName {}
use the `export` keyword when exporting source code from the current file.
// main.ts import { message, showMessage, ModuleExampleClass, POINT } from './utility'; const msg = message; showMessage(); const moduleClassInstance = new ModuleExampleClass(1234); const value = moduleClassInstance.getValue(); const coordinates: POINT = { xAxis: 10, yAxis: 20} console.log(coordinates) // Output: { "xAxis": 10, "yAxis": 20 }
// main.ts import { message, showMessage, ModuleExampleClass } from './utility'; const msg = message; showMessage(); const moduleClassInstance = new ModuleExampleClass(1234); const value = moduleClassInstance.getValue();
// utility.ts const message: string = "Module Example Through Import and Export"; function showMessage(): void { console.log(message); } class ModuleExampleClass { private value: number; constructor(value: number) { this.value = value; } getValue(): number { return this.value; } } export { message, showMessage, ModuleExampleClass }
// utility.ts export const message: string = "Module Example Through Import and Export"; export function showMessage(): void { console.log(message); } export class ModuleExampleClass { private value: number; constructor(value: number) { this.value = value; } getValue(): number { return this.value; } } export interface POINT { xAxis: number; yAxis: number; zAxis?: number; // Optional value using `?` symbol }
Use export to expose elements (variables, functions, classes) from a module.
Use import to bring in elements from a module into another file.
File extensions (like .ts or .js) are optional in the import statement.
Relative paths ('./utility') are commonly used for file imports.
Modules can also have default exports using export default.