Typescript Pt. 7 - Modules with TypeScript
Modules in TypeScript
- Modules are a way to organize code in a file.
- It helps to keep the code clean, organized, and easy to maintain.
- The general idea is to split the code into multiple files. A basic example is to split the code into a
main.tsfile and autils.tsfile as shown below.
1
2
3
4
// main.ts
import { add } from "./utils";
console.log(add(1, 2));
1
2
3
4
5
6
7
8
// utils.ts
export function add(a: number, b: number): number {
return a + b;
}
export function subtract(a: number, b: number): number {
return a - b;
}
- The
main.tsfile imports theaddfunction from theutils.tsfile. - The
addfunction is exported from theutils.tsfile using theexportkeyword. - The
addfunction is imported in themain.tsfile using theimportkeyword. - The
addfunction is used in themain.tsfile. - The
utils.tsfile contains two functions,addandsubtract.
Using the export Keyword
- The
exportkeyword is used to export a function, variable, or class from a module. - The
exportkeyword can be used with thefunctionkeyword to export a function. - It tells that we are working with Modules.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// utils.ts
export function add(a: number, b: number): number {
return a + b;
}
export function randomIt<T>(arg: T[]): T {
const idx = Math.floor(Math.random() * arg.length);
return arg[idx];
}
// main.ts
import { add, randomIt } from "./utils.js";
console.log(add(1, 2));
console.log(randomIt([1, 2, 3, 4, 5]));
Setting the module Option
- The
moduleoption in thetsconfig.jsonfile is used to specify the module code generation. - The
moduleoption can be set tocommonjs,amd,system,umd,es2015,es2020, oresnext. - The
moduleoption is set tocommonjsby default. - In order to use the
importandexportkeywords, themoduleoption must be set toes2015or higher in thetsconfig.jsonfile.
1
2
3
4
5
{
"compilerOptions": {
"module": "es2015"
}
}
- In the index.html file, we need to add the
type="module"attribute to the script tag.
1
<script type="module" src="main.js"></script>
Importing and Exporting Types
- The
exportkeyword can be used with thetypekeyword to export a type. - The
importkeyword can be used with thetypekeyword to import a type.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// utils.ts
export type User = {
id: number;
name: string;
username: string;
email: string;
address: {
street: string;
suite: string;
city: string;
zipcode: string;
geo: {
lat: string;
lng: string;
};
};
phone: string;
};
// main.ts
import { User } from "./utils.js";
const user: User = {
id: 1,
name: "Leanne Graham",
username: "Bret",
email: "user@gmail.com",
address: {
street: "Kulas Light",
suite: "Apt. 556",
city: "Gwenborough",
zipcode: "92998-3874",
geo: {
lat: "-37.3159",
lng: "81.1496",
};
};
phone: "1-770-736-8031 x56442",
};
This post is licensed under CC BY 4.0 by the author.