Typescript模块化导入导出怎么做

   2024-10-10 3580
核心提示:在Typescript中,可以使用export关键字导出模块,使用import关键字导入模块。以下是一些常用的模块导入导出示例:导出一个变量或

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

导出一个变量或函数:
// module.tsexport const myVariable: string = "Hello";export function myFunction(): void {  console.log("Function called");}// 使用模块import { myVariable, myFunction } from './module';console.log(myVariable); // 输出: HellomyFunction(); // 输出: Function called
导出一个类:
// module.tsexport class MyClass {  constructor() {    console.log("Class constructor called");  }}// 使用模块import { MyClass } from './module';const myClass = new MyClass(); // 输出: Class constructor called
导出默认模块:
// module.tsexport default function myDefaultFunction(): void {  console.log("Default function called");}// 使用模块import myDefaultFunction from './module';myDefaultFunction(); // 输出: Default function called

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

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号