温馨提示×

Typescript模块化导入导出怎么做

小樊
84
2024-06-14 19:45:28
栏目: 编程语言

在Typescript中,可以使用export关键字导出模块,使用import关键字导入模块。以下是一些常用的模块导入导出示例:

  1. 导出一个变量或函数:
// module.ts
export const myVariable: string = "Hello";
export function myFunction(): void {
  console.log("Function called");
}

// 使用模块
import { myVariable, myFunction } from './module';

console.log(myVariable); // 输出: Hello
myFunction(); // 输出: Function called
  1. 导出一个类:
// module.ts
export class MyClass {
  constructor() {
    console.log("Class constructor called");
  }
}

// 使用模块
import { MyClass } from './module';

const myClass = new MyClass(); // 输出: Class constructor called
  1. 导出默认模块:
// module.ts
export default function myDefaultFunction(): void {
  console.log("Default function called");
}

// 使用模块
import myDefaultFunction from './module';

myDefaultFunction(); // 输出: Default function called

需要注意的是,如果使用export default导出模块,则在导入时不需要使用花括号,直接使用import moduleName from './module'即可。

0