Introduction
Modules help organize code by splitting it into smaller parts. They keep code clean and avoid mixing everything together.
Modules help organize code by splitting it into smaller parts. They keep code clean and avoid mixing everything together.
export function greet() { console.log('Hello!'); } import { greet } from './greetModule'; greet();
export makes code available outside the file.
import brings code from another file to use it.
export const pi = 3.14; import { pi } from './math'; console.log(pi);
export default to export a single main item from a module.export default function sayHi() { console.log('Hi!'); } import sayHi from './sayHi'; sayHi();
This example shows how to export a function from one file and import it in another to use it.
// file: mathUtils.ts export function add(a: number, b: number): number { return a + b; } // file: app.ts import { add } from './mathUtils'; const result = add(5, 3); console.log('Sum is', result);
Modules help avoid naming conflicts by keeping code inside their own space.
Using modules makes your code easier to read and maintain.
TypeScript modules follow the same rules as ES6 JavaScript modules.
Modules split code into smaller, manageable parts.
They help share code between files safely.
Modules keep code organized and prevent conflicts.
greet from a TypeScript module?export function functionName() {}.// file1.ts
export const value = 42;// file2.ts
import { value } from './file1';
console.log(value);file2.ts is run?value with 42. file2.ts imports it correctly.console.log(value) prints 42.export const a = 10;
const b = 20;
import { b } from './moduleB';
// mathUtils.ts
export function add(x: number, y: number) { return x + y; }
export function multiply(x: number, y: number) { return x * y; }// app.ts
import * as math from './mathUtils';
console.log(math.add(2, 3));
console.log(math.multiply(4, 5));import * as math helpful in this case?math avoids naming conflicts and keeps code organized.Pass the test and this pattern moves unknown