Typescript:如何导入其他TypeScript文件? (附实例)

1,776 阅读1分钟

import other TypeScript files using import and export examples

有时,我们有一个在类型稿中声明的代码或类,想在另一个文件中导入。这是一个重复使用代码的概念。

Typescript提供了模块、导出和导入关键字来重用和向外界展示文件。

让我们看看可重用代码的不同方式。

单个类的导出和导入

在Employee.Module.ts中声明classinterfaces

export 关键字声明了可以在另一个文件中重复使用的类或函数。

Employee.Module.ts

export class Employee {

    id: number;
    name: string;
    
    constructor(id: number, name: string ) {
            this.id = id;
            this.name = name;
    }
      printEmployeeInfo():void {
        console.log("Id = " + this.id +  ", name = " + this.name);
    }
}

在TestEmployee.ts文件中,使用import 关键字将类导入其中,包括了单类,可以重复使用该类的所有类和函数

TestEmployee.ts

import { Employee } from "./Employee.Module";
let employee = new Employee(11,"John");
employee.printEmployeeInfo();

使用import 作为关键字的所有类和接口

在文件中,声明了所有这些都在一个单独的文件中使用export 关键字导出。

Employee.Module.ts

export class Lion {

    
      printLion():void {
        console.log("animal class");
    }
}
export interface Animal {


      printAnimal():void ;
}
export function printCat(){
        console.log("cat class");
      }
}

接下来,让我们使用import * as 语法将Employee.Module.ts导入另一个文件,如下图所示

TestEmp.ts

import * as Employee from "./Employee.module.ts";
let empObject = new Employee();
console.log(empObject.printLion()); //access class
console.log(Employee.printCat()); // use function

单个函数的导出和导入作为一个关键词使用

让我们在Employee.module.ts中声明一个函数,并使用export关键字进行导出。Employee.module.ts:

export function print() {
    return "print an object";
}

使用 import as wrapped in braces 语法导入这个单一的函数。

TestPrint.ts

import { print as display } from "./Employee.module";
display();

结论

学会了如何导入另一个typescript文件并在其他typescript文件中重复使用模块的类、函数、接口和属性。