DEV Community

Bobby Hall Jr
Bobby Hall Jr

Posted on • Edited on

Part 4: Working with Modules and Imports in TypeScript

Section 4: Working with Modules and Imports

In this section, we will explore modules and imports in TypeScript. Modules provide a way to organize our code into separate files and promote reusability. We will learn how to create modules, export and import components, and leverage the power of module systems.

Introduction to Modules

Modules in TypeScript are a way to encapsulate code within separate files. Each file can be treated as a module, with its own scope and dependencies. This promotes code organization, reusability, and maintainability.

To define a module, we use the export keyword to mark the components that we want to make available outside the module.

// math.ts
export function sum(a: number, b: number): number {
  return a + b;
}

export const PI = 3.14;
Enter fullscreen mode Exit fullscreen mode

Exporting and Importing Modules

To use components from another module, we need to import them. We use the import keyword to specify the module and the components we want to import.

// app.ts
import { sum, PI } from "./math";

console.log(sum(5, 10)); // 15
console.log(PI); // 3.14
Enter fullscreen mode Exit fullscreen mode

We can also use the import statement with an alias to rename imported components.

import { sum as add } from "./math";
console.log(add(5, 10)); // 15
Enter fullscreen mode Exit fullscreen mode

Default Exports and Imports

A module can have a default export, which represents the main exported component. It can be imported using the import statement without curly braces.

// math.ts
export default function multiply(a: number, b: number): number {
  return a * b;
}

// app.ts
import multiply from "./math";
console.log(multiply(5, 10)); // 50
Enter fullscreen mode Exit fullscreen mode

Organizing Code with Module Systems

TypeScript supports various module systems, including CommonJS, AMD, and ES modules. The module system used depends on the target environment and the module loader being used.

To specify the module system, we can use the module compiler option in the tsconfig.json file.

{
  "compilerOptions": {
    "module": "commonjs"
  }
}
Enter fullscreen mode Exit fullscreen mode

TypeScript provides flexibility in choosing the module system based on the specific needs of the project.

Conclusion

Modules and imports are powerful features of TypeScript that allow us to organize and modularize our codebase effectively. They promote reusability, maintainability, and better code organization. By leveraging modules, we can build scalable and maintainable applications.


In the next section, we will explore asynchronous programming with TypeScript, including promises, async/await, error handling, and working with async functions.


Subscribe to my newsletter where you will get tips, tricks and challenges to keep your skills sharp. Subscribe to newsletter


Buy Me A Coffee

Top comments (0)