This chapter introduces TypeScript modules, a powerful mechanism for organizing and managing code. Modules allow developers to break down applications into reusable and maintainable units, promoting modular programming and better code management.
Chapter Goal
- To understand what TypeScript modules are and their purpose.
- To learn how to create, import, and export modules.
- To explore practical applications of modules in TypeScript projects.
Key Characteristics for TypeScript Modules
- Code Encapsulation: Encapsulates logic into separate files for clarity and reuse.
- Named and Default Exports: Supports multiple ways to export and import.
- Dependency Management: Resolves dependencies between different parts of the code.
- Isolation: Avoids name collisions by maintaining a local scope for each module.
- Compatibility: Integrates seamlessly with JavaScript and modern module systems.
Basic Rules for TypeScript Modules
- Use export to expose functions, classes, or variables from a module.
- Use import to include functions, classes, or variables from another module.
- Always include a module resolution strategy (e.g., ES Modules or CommonJS).
- Avoid circular dependencies between modules.
- Group related functionalities into a single module for better organization.
Best Practices
- Use meaningful file and module names to indicate their purpose.
- Prefer named exports for better flexibility and clarity.
- Organize modules into directories for large projects.
- Document the functionality of modules to improve maintainability.
- Test modules independently before integrating them into the main application.
Syntax Table
Serial No | Component | Syntax Example | Description |
1 | Named Export | export const add = (a: number, b: number) => a + b; | Exports a named function or variable. |
2 | Default Export | export default function greet() {} | Exports a default function or class. |
3 | Import Named Export | import { add } from ‘./math’; | Imports a specific named export from a module. |
4 | Import Default Export | import greet from ‘./greetings’; | Imports the default export from a module. |
5 | Wildcard Import | import * as Utils from ‘./utilities’; | Imports all exports from a module into a namespace. |
Syntax Explanation
1. Named Export
What is a Named Export
A mechanism in TypeScript that allows developers to export multiple functions, classes, or variables individually by name. This approach provides flexibility by enabling selective imports and better organization when modules expose multiple functionalities.
Syntax
// math.ts
export const add = (a: number, b: number) => a + b;
export const subtract = (a: number, b: number) => a – b;
Detailed Explanation
- Exports add and subtract functions by name.
- Consumers can selectively import the required functions.
Example
// main.ts
import { add, subtract } from ‘./math’;
console.log(add(5, 3)); // Output: 8
console.log(subtract(5, 3)); // Output: 2
Output
8
2
Notes
- Use named exports for functions or variables shared across multiple files.
Warnings
- Ensure export names do not conflict with imports in the consuming module.
2. Default Export
What is a Default Export
A mechanism in TypeScript that enables the export of a single function, class, or object as the primary feature of a module. This simplifies the import process by allowing consumers to access the module’s main functionality without needing to specify a name in curly braces.
Syntax
// greetings.ts
export default function greet(): void {
console.log(‘Hello, World!’);
}
Detailed Explanation
- The default export does not require curly braces during import.
- Each module can have only one default export.
Example
// main.ts
import greet from ‘./greetings’;
greet(); // Output: Hello, World!
Output
Hello, World!
Notes
- Use default exports for modules exposing a single functionality.
Warnings
- Avoid mixing default and named exports in the same module for simplicity.
3. Import Named Export
What is Import Named Export
A mechanism in TypeScript that allows developers to import only the specific functionalities they need from a module. This approach reduces unnecessary imports, optimizes performance by enabling tree-shaking, and improves clarity by explicitly stating what is being used.
Syntax
import { add } from ‘./math’;
Detailed Explanation
- Allows importing only the required functionalities from a module.
- Helps reduce the size of the imported code when tree-shaking is enabled.
Example
// main.ts
import { add } from ‘./math’;
console.log(add(10, 20)); // Output: 30
Output
30
Notes
- Use named imports to avoid importing unnecessary code.
Warnings
- Ensure the import statement matches the exact export name.
4. Import Default Export
What is Import Default Export
A concise and straightforward syntax in TypeScript used to import the primary functionality of a module that has been designated as the default export. This approach simplifies usage by omitting the need for curly braces and allows developers to focus on the main purpose of the module.
Syntax
import greet from ‘./greetings’;
Detailed Explanation
- No curly braces are needed when importing the default export.
- Each module can have only one default export, simplifying its usage.
Example
// main.ts
import greet from ‘./greetings’;
greet(); // Output: Hello, World!
Output
Hello, World!
Notes
- Use default imports for modules exposing one primary functionality.
Warnings
- Avoid using ambiguous names for default imports to maintain clarity.
5. Wildcard Import
What is a Wildcard Import
A flexible syntax in TypeScript that allows developers to group all exports from a module under a single namespace. This approach simplifies access to multiple functionalities within the module, providing a clear and organized way to use utility functions or related features without importing them individually.
Syntax
import * as Utils from ‘./utilities’;
Detailed Explanation
- Groups all exports under a single namespace (e.g., Utils).
- Useful for importing utility modules with multiple functions.
Example
// utilities.ts
export const add = (a: number, b: number) => a + b;
export const subtract = (a: number, b: number) => a – b;
// main.ts
import * as Utils from ‘./utilities’;
console.log(Utils.add(4, 2)); // Output: 6
console.log(Utils.subtract(4, 2)); // Output: 2
Output
6
2
Notes
- Use wildcard imports for utility or helper modules.
Warnings
- Avoid wildcard imports in modules with too many exports to reduce namespace clutter.
Real-Life Project
Project Name
E-Commerce Utilities
Project Goal
Demonstrates how to use modules for organizing reusable utility functions in an e-commerce application.
Code for This Project
// priceCalculator.ts
export function calculateDiscount(price: number, discount: number): number {
return price - price * (discount / 100);
}
export function calculateTax(price: number, taxRate: number): number {
return price + price * (taxRate / 100);
}
// main.ts
import { calculateDiscount, calculateTax } from './priceCalculator';
const discountedPrice = calculateDiscount(100, 10);
const finalPrice = calculateTax(discountedPrice, 5);
console.log(`Discounted Price: $${discountedPrice}`); // Output: Discounted Price: $90
console.log(`Final Price with Tax: $${finalPrice}`); // Output: Final Price with Tax: $94.5
Save and Run
- Save the code in your development environment, such as Visual Studio Code, ensuring the files are named priceCalculator.ts and main.ts.
- Compile the TypeScript code into JavaScript using the command tsc.
- Execute the resulting JavaScript file using the command node main.js.
Expected Output
Discounted Price: $90
Final Price with Tax: $94.5
Insights
- Modules enhance code organization and reusability by grouping related functionalities.
- Named and default exports provide flexibility in how modules are consumed.
- Real-world applications like e-commerce utilities highlight the practical utility of modules.
Key Takeaways
- TypeScript modules encapsulate code, making it reusable and maintainable.
- Use named exports for multiple functionalities and default exports for single-purpose modules.
- Organize large projects into modular structures for better scalability and maintainability.