ES module syntax translates this sentence into English, output only plain text directly, do not output anything else.
ES module syntax is the standard way to organize and share code in JavaScript, and TypeScript provides full support for it. Modular development makes code easier to maintain and reuse while enhancing reliability through static type checking.
Basic Concepts of Modules
A module is an independent file containing specific functionality, interacting with other modules through export
and import
statements. Each module has its own scope, avoiding global pollution.
// math.ts
export function add(a: number, b: number): number {
return a + b
}
export const PI = 3.1415926
Export Declarations
TypeScript supports various export methods, including named exports and default exports.
Named Exports
// utilities.ts
export function formatDate(date: Date): string {
return date.toISOString()
}
export interface User {
id: number
name: string
}
Default Exports
Each module can have one default export:
// Logger.ts
export default class Logger {
log(message: string): void {
console.log(`[LOG] ${message}`)
}
}
Import Statements
The import method must correspond to the export method.
Named Imports
import { add, PI } from './math'
console.log(add(2, 3)) // 5
console.log(PI) // 3.1415926
Default Imports
import Logger from './Logger'
const logger = new Logger()
logger.log('Hello world')
Renaming Imports and Exports
Use the as
keyword to rename:
// Rename when exporting
export { add as sum } from './math'
// Rename when importing
import { formatDate as fd } from './utilities'
console.log(fd(new Date()))
Namespace Imports
Import an entire module as a namespace:
import * as math from './math'
console.log(math.add(1, 2))
console.log(math.PI)
Dynamic Imports
Use the import()
function for on-demand loading:
async function loadModule() {
const module = await import('./math')
console.log(module.add(10, 20))
}
Type Exports and Imports
TypeScript can export types separately:
// types.ts
export type Point = {
x: number
y: number
}
// Usage
import type { Point } from './types'
Module Resolution Strategies
TypeScript supports two module resolution strategies:
- Classic: TypeScript's traditional resolution method
- Node: Emulates Node.js's module resolution logic
Configuration example:
{
"compilerOptions": {
"moduleResolution": "node"
}
}
Path Aliases
Simplify import paths with paths
configuration:
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"@utils/*": ["utils/*"]
}
}
}
Usage example:
import { format } from '@utils/string'
Modules and Namespaces
Although namespaces can also organize code, modules are the more modern approach:
// Not recommended
namespace Math {
export function add(a: number, b: number) {
return a + b
}
}
// Recommended
export module Math {
export function add(a: number, b: number) {
return a + b
}
}
Module Side Effects
Some modules execute initialization code, which can be marked like this:
import './init' // This import will execute the module's code
Circular Dependencies
Mutual references between modules may cause circular dependencies, which should be handled carefully:
// a.ts
import { b } from './b'
export function a() {
b()
}
// b.ts
import { a } from './a'
export function b() {
a() // May cause stack overflow
}
Modules and CommonJS Interoperability
TypeScript can handle CommonJS modules:
import fs = require('fs') // CommonJS import
import * as fs from 'fs' // ES module import
Module Metadata
Access module information via import.meta
:
console.log(import.meta.url) // Current module's URL
Module Compilation Targets
TypeScript can compile to different module systems:
{
"compilerOptions": {
"module": "es2020" // Can also be commonjs, umd, etc.
}
}
Module Code Splitting
Combine with bundlers for code splitting:
// Dynamic imports automatically enable code splitting
const module = await import('./heavy-module')
Module Type Declarations
Add type declarations for third-party modules:
// custom.d.ts
declare module 'custom-module' {
export function doSomething(): void
}
Module Testing
Import modules directly for testing:
// math.test.ts
import { add } from './math'
test('adds numbers', () => {
expect(add(1, 2)).toBe(3)
})
Module Bundling Optimization
Use sideEffects
to help bundlers optimize:
{
"sideEffects": false
}
Module Browser Support
Modern browsers natively support ES modules:
<script type="module" src="app.js"></script>
Module Performance Considerations
Organizing module structure properly can optimize loading performance:
// Avoid deeply nested imports
import { util } from '../../../../utils' // Not recommended
import { util } from '@project/utils' // Recommended
Module Debugging
Browser developer tools support module debugging:
// Set breakpoints to step through module code
debugger
const result = add(1, 2)
Module Version Management
Manage module versions with npm:
{
"dependencies": {
"lodash": "^4.17.21"
}
}
Module Security Considerations
Be mindful of dependency security:
npm audit # Check for security vulnerabilities
Module Documentation Generation
Use tools to auto-generate documentation:
/**
* Calculates the sum of two numbers
* @param a First number
* @param b Second number
* @returns Sum of the two numbers
*/
export function add(a: number, b: number): number {
return a + b
}
Module Code Style
Maintain consistent import order:
// 1. Third-party modules
import React from 'react'
// 2. Project modules
import { Button } from './components'
// 3. Styles and assets
import './styles.css'
Module Extensibility
Design modules with extensibility in mind:
// Base module
export abstract class Storage {
abstract get(key: string): Promise<string>
}
// Extended implementation
export class LocalStorage extends Storage {
// Implementation details
}
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn