This article explores importing and exporting modules in TypeScript, covering syntaxes, configuration tips, and best practices for effective code modularization.
In this article, we explore how to import and export modules in TypeScript. We’ll cover various syntaxes, project configuration tips, and best practices to help you modularize your code effectively.
Importing enables you to break your codebase into smaller, manageable files, promoting modularity and code reuse. If you’re coming from other programming languages, you’ll notice that splitting code into multiple files is a common practice.Consider the following import syntaxes:
Copy
Ask AI
// Basic Syntax:import { exportedMember } from './fileName';// Importing Default Exports:import defaultExport from './fileName';// Importing Everything:import * as utils from './utils';
When beginning a new TypeScript project, it’s important to set up your dependencies and development server correctly. For example, after starting your project, run:
Copy
Ask AI
yarn install
Then, launch your development server with:
Copy
Ask AI
yarn dev
This should display “Importing in TypeScript!” in your console, confirming your project is set up properly.
Suppose you have a file containing utility functions. In that file, you might define:
Copy
Ask AI
export function multiply(a: number, b: number): number { return a * b;}export function divide(a: number, b: number): number { if (b === 0) throw new Error('Division by zero is not allowed.'); return a / b;}
Then, in your main file (e.g., index.ts), you could simply log a statement:
Copy
Ask AI
console.log('Importing in TypeScript!');
When you run yarn dev, you might see output similar to:
Copy
Ask AI
[INFO] ... ts-node-dev ver. 2.0.0 ...Importing in TypeScript!
A module can also export a default function. For instance:
Copy
Ask AI
export default function calculateTotal(prices: number[]): number { return prices.reduce((total, price) => total + price, 0);}
You can import this default export without referencing its original name:
Copy
Ask AI
import calculateTotal from './import-examples/calculator';import { add } from './import-examples/mathUtils';console.log('Importing in TypeScript!', calculateTotal([1, 2, 3]));
This logs the calculated total (6) to the console. Default exports also offer flexibility, as you can rename them upon import.
To import every exported member from a module, use the star syntax. For example, given a module with both multiply and divide functions:
Copy
Ask AI
import * as utils from './import-examples/utils';// Using the imported functions via the 'utils' objectconsole.log('Importing in TypeScript!', utils.multiply(1, 2), utils.divide(2, 2));
This will log the results of the multiplication (2) and division (1) respectively.
Third-party libraries can be imported just as easily as local modules. For example, if you install Lodash as a dependency, import and utilize its functions like so:
Copy
Ask AI
import _ from 'lodash';// Using Lodash's add function to add two numbersconsole.log('Importing in TypeScript!', _.add(2, 3));
This demonstrates the seamless integration of npm packages into your TypeScript project.
In larger applications—such as APIs or Infrastructure as Code projects—a main entry point is common. Projects often use index.ts or main.ts to serve this purpose.
You might log some output and export a main function with a default export:
Copy
Ask AI
import calculateTotal from './import-examples/calculator';import { add } from './import-examples/mathUtils';import * as utils from './import-examples/utils';import _ from 'lodash';// Log a result using Lodash's add functionconsole.log('Importing in TypeScript!', _.add(2, 3));// Exporting a main function as a default exportexport default function main() { console.log('Main running');}
Alternatively, export the main function as a named export:
Copy
Ask AI
import calculateTotal from './import-examples/calculator';import { add } from './import-examples/mathUtils';import * as utils from './import-examples/utils';import _ from 'lodash';console.log('Importing in TypeScript!', _.add(2, 3));export const main = () => { console.log('Main running');};
Both methods ensure that your application’s runtime environment can correctly identify and execute the entry point.
In this article, we covered several methods for importing and exporting modules in TypeScript using modern ECMAScript Module (ESM) syntax. The key topics included:
Basic named exports and default exports
Utilizing the star syntax to import all exports from a module
Importing third-party libraries like Lodash
Exporting a main entry point for your application
While TypeScript does support CommonJS syntax, ESM is the preferred modern method for writing and structuring applications.
In the next section, we will dive into configuring TypeScript for your projects and explore additional best practices.Happy coding!