Import and Export
In this page:
Named Export Syntax
Writing export before a declaration makes it available to other modules as a named export, which other files can then bring in with a matching import statement. A single file can have as many named exports as it needs, each imported individually or together.
Example: Named Export Syntax
// utils.ts
export function add(a: number, b: number): number {
return a + b;
}
export const VERSION = "1.0";
console.log(add(2, 3), VERSION);
Importing Multiple Values
Multiple named exports can be imported together inside curly braces in a single import statement, rather than requiring a separate import line for each individual export, keeping the top of a file's imports compact and easy to scan.
Example: Importing Multiple Values
// utils.ts
export function add(a: number, b: number) { return a + b; }
export function subtract(a: number, b: number) { return a - b; }
// main.ts
// import { add, subtract } from "./utils";
console.log(add(5, 2), subtract(5, 2));
Export Lists
Declarations can be written first and exported later using a separate export list at the bottom of the file, which can make a module's public surface easier to scan at a glance.
Example: Export Lists
function add(a: number, b: number) {
return a + b;
}
function subtract(a: number, b: number) {
return a - b;
}
export { add, subtract };
console.log(add(1, 1));
Re-exporting Values
A module can re-export declarations that it itself imported from another module, which is useful for creating a single central entry-point file that gathers scattered exports together.
Example: Re-exporting Values
// math.ts
export function square(x: number) { return x * x; }
// index.ts
// export { square } from "./math";
function square(x: number) { return x * x; }
console.log(square(4));
Type-Only Imports and Exports
Use import type and export type when a declaration is needed only for type checking, since these type-only imports are guaranteed to be stripped out entirely from the compiled JavaScript output.
Example: Type-Only Imports and Exports
interface User {
name: string;
}
export type { User };
// main.ts
// import type { User } from "./user";
const u: User = { name: "Ravi" };
console.log(u.name);
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: