A module in TypeScript is a file that contains code and can export parts of that code to other files for use in other files.
This allows us to break our code into smaller modules and maintain an organized and modular structure in our project.
Creating a Module in TypeScript
To create a module in TypeScript, we simply need to use the export
keyword before the declaration of a class, function, constant, or variable that we want to make accessible from other files. Let’s see an example:
// file: utils.ts
export function sum(a: number, b: number): number {
return a + b;
}
export const PI = 3.1416;
export default class Person {
constructor(public name: string) {}
}
In the previous example,
- We created a module called
utils.ts
- This exports a class
Person
as the default - Exports a function
sum
and a named constantPI
.
These functionalities can now be imported and used in other TypeScript files.
Exporting the Module
Default Export
We can export a single entity by default from a module using the export default
keyword. This allows us to import that entity without needing to use destructuring braces.
export default class MyClass {
// Class code
}
To import the entity exported by default, we simply use the name we want to assign it in our import.
import MyClass from './path/to/module';
Named Export
We can also export multiple entities from a module using the export
keyword followed by the name of the entity we want to export.
export class Class1 {
// Class code
}
export interface Interface1 {
// Interface code
}
Exporting with Alias
It is possible to use an alias for the export of an entity using the as
keyword followed by the alias name.
export { entityName as alias } from './path/to/module';
Importing Modules
Importing modules allows us to use the exported code from another file in our own file.
To import a module in TypeScript, we use the import
keyword followed by the name of the module we want to import.
import { moduleName } from './path/to/module';
To use the exported elements from a module in another TypeScript file, we must import them. The syntax for importing a module is as follows:
import Person from './utils';
In the previous example,
- We are also importing the
Person
class using the default import syntax.
Importing Multiple Elements
If we need to import more than one element, we can use the destructuring braces syntax in our import.
import { Class1, Interface1 } from './path/to/module';
For example:
import { sum, PI } from './utils';
In the previous example,
- We are importing the
sum
function and thePI
constant from theutils.ts
module.