程序员的知识教程库

网站首页 > 教程分享 正文

一文搞懂es6的import、export(es6import用法)

henian88 2024-09-09 03:45:15 教程分享 13 ℃ 0 评论

对导出的模块进行重命名

export { moduleA as mA } from './xxx'

对导入的模块进行重命名

import { moduleB as mB } from './xxx'
let mb = new mB()

将整个模块导入到一个变量,并通过它来访问模块的导出部分

import * as validator from './xxx'
let myValidator = new validator.valida()

若使用export =导出一个模块,则必须使用TypeScript的特定语法import module = require("module")来导入此模块

// ZipCodeValidator.ts
let numberRegexp = /^[0-9]+$/;
class ZipCodeValidator {
    isAcceptable(s: string) {
        return s.length === 5 && numberRegexp.test(s);
    }
}
export = ZipCodeValidator;
// Test.ts
import zip = require("./ZipCodeValidator");
let validator = new zip()
let strings = ["Hello", "98052", "101"];
strings.forEach(s => {
  console.log(`"${ s }" - ${ validator.isAcceptable(s) ? "matches" : "does not match" }`);
});

使用注意事项:

如果仅导出单个 class 或 function,使用 export default

如果要导出多个对象,把它们放在顶层里导出

// a.ts
export class SomeType { /* ... */ }
export function someFunc() { /* ... */ }
// b.ts
import { SomeType, someFunc } from "./MyThings";
let x = new SomeType();
let y = someFunc();

当你要导出大量内容的时候,使用命名空间导入模式

// a.ts
export class Dog { ... }
export class Cat { ... }
export class Tree { ... }
export class Flower { ... }
// b.ts
import * as mA from "./a.ts";
let x = new mA.Dog();
let y = new mA.Tree();

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表