fe-interview
                                
                                
                                
                                    fe-interview copied to clipboard
                            
                            
                            
                        [TypeScript] 第1518天 在TypeScript中如何定义、导入和导出模块?
可以使用export关键字导出模块,使用import关键字导入模块。
在 TypeScript 中,模块系统用于将代码组织成独立的文件和片段。通过模块,你可以将代码拆分成多个文件,并在这些文件之间共享代码。TypeScript 支持两种模块语法:ES6 模块和 CommonJS 模块。以下是如何定义、导入和导出模块的详细说明。
使用 ES6 模块
1. 定义和导出模块
你可以使用 export 关键字导出变量、函数、类或接口。
// math.ts
export const PI = 3.14;
export function add(a: number, b: number): number {
    return a + b;
}
export class Circle {
    constructor(public radius: number) {}
    getArea(): number {
        return PI * this.radius * this.radius;
    }
}
2. 导入模块
你可以使用 import 关键字导入其他模块导出的内容。
// main.ts
import { PI, add, Circle } from './math';
console.log(`PI: ${PI}`);
console.log(`3 + 4 = ${add(3, 4)}`);
const myCircle = new Circle(5);
console.log(`Area of my circle: ${myCircle.getArea()}`);
3. 导出和导入默认导出
默认导出使用 export default 关键字,并且导入时不需要使用花括号。
// logger.ts
export default function log(message: string): void {
    console.log(`Log: ${message}`);
}
// main.ts
import log from './logger';
log('Hello, TypeScript!');  // 输出: Log: Hello, TypeScript!
4. 重新导出
你可以从一个模块中重新导出另一个模块的导出内容。
// shapes.ts
export * from './math';
使用 CommonJS 模块
在 Node.js 环境中,CommonJS 模块更常见。你可以使用 module.exports 和 require 来导出和导入模块。
1. 定义和导出模块
// math.js
const PI = 3.14;
function add(a, b) {
    return a + b;
}
class Circle {
    constructor(radius) {
        this.radius = radius;
    }
    getArea() {
        return PI * this.radius * this.radius;
    }
}
module.exports = { PI, add, Circle };
2. 导入模块
// main.js
const { PI, add, Circle } = require('./math');
console.log(`PI: ${PI}`);
console.log(`3 + 4 = ${add(3, 4)}`);
const myCircle = new Circle(5);
console.log(`Area of my circle: ${myCircle.getArea()}`);
使用 TypeScript 配置文件 (tsconfig.json)
为了使用模块系统,需要在 tsconfig.json 中配置 module 选项。
{
  "compilerOptions": {
    "module": "commonjs", // 或 "es6"
    "target": "es6",
    "outDir": "./dist",
    "rootDir": "./src"
  }
}
总结
在 TypeScript 中,定义、导入和导出模块可以帮助你组织代码,使其更加模块化和可维护。ES6 模块语法是现代 JavaScript 和 TypeScript 开发的推荐方式,但在 Node.js 环境中,CommonJS 模块也很常见。通过合理使用模块,你可以提高代码的可读性和可维护性。
以下是一个综合示例,展示了如何定义、导入和导出模块:
math.ts
export const PI = 3.14;
export function add(a: number, b: number): number {
    return a + b;
}
export class Circle {
    constructor(public radius: number) {}
    getArea(): number {
        return PI * this.radius * this.radius;
    }
}
logger.ts
export default function log(message: string): void {
    console.log(`Log: ${message}`);
}
main.ts
import { PI, add, Circle } from './math';
import log from './logger';
console.log(`PI: ${PI}`);
console.log(`3 + 4 = ${add(3, 4)}`);
const myCircle = new Circle(5);
console.log(`Area of my circle: ${myCircle.getArea()}`);
log('This is a log message.');
通过这种方式,你可以在 TypeScript 中使用模块化的代码组织方式,提高代码的结构和可维护性。