TypeScript Modules
A module is a file that exports values for other files to use. An import brings a named export into the file that needs it.
The math.ts file
This file exports two functions and one constant. It prints nothing on its own.
export function add(a: number, b: number): number {
return a + b;
}
export function multiply(a: number, b: number): number {
return a * b;
}
export const PI = 3.14;Import one function in main.ts
The import names add and the file it comes from. The call then works like a local function.
import { add } from "./math";
console.log(add(2, 3));Import the constant in main.ts
One import can bring in several names at once. This file takes the other function and the constant.
import { multiply, PI } from "./math";
console.log(multiply(4, 5));
console.log(PI);Example
import { add, multiply, PI } from "./math";
const radius = 3;
const area = multiply(PI, multiply(radius, radius));
console.log(area);
console.log(add(10, 5));Key points
- The export keyword makes a value available to other files
- An import names the values it needs and the file they come from
- A file with at least one export is a module
- A module can also have one default export, written with export default
- An import can rename a value with as, so add can arrive as sum
In this example, main.ts imports add, multiply and PI from math.ts. The inner multiply call squares the radius. The outer call multiplies that square by PI to give the area. The last line adds two numbers with the imported add function.
Note
Import paths for local files start with ./ and name the file without its extension in this course
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
What does the export keyword do in a module?