The TypeScript module system
The module system is the foundation of modern TypeScript development.
TypeScript fully supports ES Module syntax and provides rich module resolution strategies.
Through the module system, code can be split into reusable units, achieving code organization and reuse.
Why a module system is needed
As projects grow, the amount of code increases.
Dispersing code across multiple files and organizing it through modules improves code maintainability and reusability.
The module system gives each file its own scope, avoiding global variable pollution.
Concept explanation:A module is a TypeScript file containing export and import statements. Content is exported with export and imported with import.
Module exports
Using the export keyword, variables, functions, classes, interfaces, etc. can be exported for use by other modules.
The user.ts module
// Export a variable
export
var
name
=
"Alice"
;
export
const
age
=
25
;
// Export a function
export
function
greet
(
message
:
string
)
:
string
{
return
"Hello, "
message
;
}
// Export a class
export
class
User
{
// Constructor parameter property
constructor
(
public name
:
string
)
{
}
// Self-introduction method
introduce
(
)
:
string
{
return
"I am "
this
.
name
;
}
}
// Export an interface (interfaces disappear after compilation and are only used for type checking)
export
interface
Config
{
// Configure the host
host
:
string
;
// Configure the port
port
:
number
;
}
// Batch export: renamed exports
export
{
name as userName
,
age as userAge
}
;
Note:Interfaces and types do not produce actual code in the compiled JavaScript; they are only used for TypeScript's type checking.
Module import
Use the import keyword to import exported content from other modules.
main.ts imports the module
// Named import: import specified content from a module
import
{
name
,
age
,
greet
}
from
"./user"
;
// Default import: import a module's default export
import
User from
"./user"
;
// Namespace import: put all of a module's exports into one object
import
as UserModule from
"./user"
;
// Renamed import: avoid naming conflicts
import
{
greet as sayHello
}
from
"./user"
;
// Use the imported content
console.
log
(
greet
(
"World"
)
)
;
console.
log
(
sayHello
(
"TypeScript"
)
)
;
Running result:
Hello, World
Hello, TypeScript
Path notes:Import paths can be relative (such as
./user) or absolute (such as@/utils)。
Default exports
Each module can have one default export.
A default export does not require braces when imported and can be given any name.
The math.ts module
// Default export: a module can have only one default export
export
default
function
add
(
a
:
number
,
b
:
number
)
:
number
{
return
a
b
;
}
// Can be mixed with other exports
export
function
multiply
(
a
:
number
,
b
:
number
)
:
number
{
return
a
b
;
}
main.ts import
// Import the default export: can be given any name
import
add from
"./math"
;
// Import named exports: braces are required
import
{
multiply
}
from
"./math"
;
console.
log
(
"Addition: "
add
(
2
,
3
)
)
;
console.
log
(
"Multiplication: "
multiply
(
4
,
5
)
)
;
Running result:
加法: 5
乘法: 20
Note:Use default exports for main exports such as utility functions and classes, and named exports for helper functions, interfaces, etc.
Re-exports
Re-exports are used to aggregate content from multiple modules, or to expose one module's exports to another module.
The index.ts aggregation module
// Re-export specified content from other modules
export
{
name
,
age
}
from
"./user"
;
// Re-export a default export (requires renaming)
export
{
default
as User
}
from
"./user"
;
// Re-export all content
export
from
"./math"
;
Application scenarios:Use index.ts as an entry file to centrally export submodule content, making imports unified and convenient.
Module resolution strategies
TypeScript provides multiple module resolution strategies for finding imported modules.
They can be configured in tsconfig.json.
tsconfig.json configuration
{
"compilerOptions"
:
{
// Node resolution strategy
// Follow Node.js module resolution rules
"moduleResolution"
:
"node"
,
// Classic resolution strategy
// The strategy used by early versions of TypeScript
"moduleResolution"
:
"classic"
,
// base URL: set the base path
// All non-relative imports are resolved based on this path
"baseUrl"
:
"./src"
,
// Path mapping: set aliases for import paths
"paths"
:
{
// Imports starting with @ map to the src directory
"@/*"
:
[
"./*"
]
,
// Imports starting with @components map to the components directory
"@components/*"
:
[
"./components/*"
]
}
}
}
Configuration recommendations:New projects are recommended to use the Node resolution strategy, which is currently the most common approach.
Dynamic imports
Dynamic import uses the import() syntax to load modules on demand at runtime.
This is very useful for code splitting and lazy loading.
Example
// Dynamic import - lazy loading
// import() returns a Promise
async
function
loadMath
(
)
{
// Dynamically import a module; it is only loaded when execution reaches here
var
math
=
await
import
(
"./math"
)
;
// math.default is the default exported function
console.
log
(
"Dynamic addition: "
math.
default
(
1
,
2
)
)
;
}
// Call the lazy-loaded function
loadMath
(
)
;
// Conditional import: dynamically load different modules based on conditions
async
function
loadFeature
(
enable
:
boolean
)
{
if
(
enable
)
{
// The module is only loaded when the condition is met
var
feature
=
await
import
(
"./feature"
)
;
feature.
run
(
)
;
}
}
// Load based on conditions
loadFeature
(
true
)
;
Running result:
动态加法: 3
Performance optimization:Dynamic imports enable code splitting, loading additional code only when needed, reducing initial load time.
Notes
- **Relative paths:** use relative paths to import local modules (./, ../)
- **Module extensions:** TypeScript handles extensions automatically during compilation
- **Default vs. named:** one default export per module, multiple named exports
- **esModuleInterop:** enabling this option makes it easier to import CommonJS modules
Best practices:Keep import paths consistent, use path aliases to simplify long paths, and establish a clear module organization structure.
Summary
The module system is the core of TypeScript project organization.
- **export:** export variables, functions, classes, interfaces
- **import:** import exported content
- **Default export:** one per module, flexible to use
- **Re-export:** aggregate modules, create entry files
- **Dynamic import:** lazy loading, performance optimization
- **Module resolution:** configure path aliases and resolution strategies
Note:Organize module structure reasonably, use path aliases to simplify imports, and establish clear export/import conventions.