Import, Export, and Module Resolution
Learn how to organize TypeScript code using modules and namespaces. This module explains import/export syntax, module resolution, and best practices for structuring scalable applications.
1. Import and Export Syntax
Modules allow you to split code into separate files and reuse functionality across your project. TypeScript uses ES6 module syntax.
Exporting
You can export variables, functions, or classes from a module.
Importing
You can import exported members in another file.
Default Export
2. Module Resolution
Module resolution determines how TypeScript finds the files referenced in import statements.
Types of Module Resolution
- Classic
- The older strategy, used for legacy code.
- Searches relative paths without
node_modules. - Node
- Mimics Node.js resolution logic.
- Searches
node_modulesand supports extensions like.ts,.js,.json. - Default in modern TypeScript projects.
Example
tsconfig.json Settings
baseUrlandpathshelp resolve modules using aliases.- Correct module resolution ensures smooth compilation and avoids "module not found" errors.
Conclusion
Modules and namespaces in TypeScript provide a structured approach to organizing code. Understanding import/export syntax and module resolution is essential for building maintainable, scalable applications with clean separation of concerns.