In TypeScript (and modern JavaScript), modules are files that contain code with their own local scope. They help in organizing applications into small, self-contained, and reusable pieces of functionality. Each file that contains an export or importstatement is treated as a module.
By using modules, you can:
Each module can:
TypeScript modules follow the ECMAScript module standard (ESM) and useimport/export syntax by default, but they can also work withCommonJS modules for Node.js environments.
Use the export keyword to make variables or functions accessible to other modules:
// mathUtils.ts - A module exporting a function
export function add(a: number, b: number): number {
return a + b;
}
Use the import keyword to bring in exports from other files:
// main.ts - Importing from mathUtils
import { add } from './mathUtils';
console.log(add(5, 3)); // Output: 8You can also use aliases:
import * as MathUtils from './mathUtils';A module can have a single default export:
// logger.ts
export default function log(message: string) {
console.log("LOG:", message);
}Imported without curly braces:
import log from './logger';TypeScript uses a strategy (usually "Node") to resolve file paths. This is controlled by settings like baseUrl and paths in tsconfig.json. Example:
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"@utils/*": ["utilities/*"]
}
}
}Ask the AI if you need help understanding or want to dive deeper in any topic