
- Importing breaks a large codebase into smaller, focused modules so code is easier to read, test, and maintain.
- It enables code reuse across files and packages and helps prevent name collisions when combined with aliasing or namespaces.
Your editor (for example VS Code) will usually auto-complete and insert import statements for you. Rely on that to avoid manual errors.
- mathUtils.ts — named exports
- utils.ts — named exports
- calculator.ts — default export
- Aliasing:
import { add as sum } from './import-examples/mathUtils';helps avoid naming collisions when multiple modules export the same symbol name. - Namespace imports:
import * as utils from './import-examples/utils';are useful when you want a single object to group all exports (good for utility libraries). - Default exports: Use
export defaultwhen the module exports one primary value; use named exports when a module exports multiple utilities. - Prefer named exports for libraries you expect to tree-shake and for clearer IDE auto-completion.
- Keep module responsibilities small — one concept or small set of related utilities per file.
index.ts or main.ts), you can provide either a default export or named exports depending on the framework’s convention.
Examples:
- ECMAScript modules (ESM) —
import/export— are the recommended approach for modern TypeScript projects and for native support in bundlers and Node (with proper configuration). - CommonJS —
require()/module.exports— is legacy and still used in some Node ecosystems. If interoperating with CommonJS packages, you may needesModuleInteroporallowSyntheticDefaultImportsin yourtsconfig.json.
Links and references
- TypeScript: https://www.typescriptlang.org/docs/
- ECMAScript Modules (MDN): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules
- VS Code: https://code.visualstudio.com/
- Lodash (npm): https://www.npmjs.com/package/lodash