【问题标题】:Explain "export =" and "export as namespace" syntax in TypeScript解释 TypeScript 中的“export =”和“export as namespace”语法
【发布时间】:2017-12-04 11:45:28
【问题描述】:

我正在尝试使用DefinitelyTyped 存储库中的类型声明文件。其中许多文件使用以下模式:

export = React;
export as namespace React;

谷歌搜索,我发现这个引用被用来使声明文件在基于模块和非基于模块的系统中都可用。然而,我正在努力寻找一个清晰的解释:(a) 这些行中的每一个究竟是做什么的,以及 (b) 这种组合究竟是如何支持这两种类型的消费者的。

【问题讨论】:

标签: typescript


【解决方案1】:

第一种形式用于 CommonJS 和 AMD 模块系统。您必须将export = Reactimport React = require('./React') 匹配

参见documentation,它给出了这个例子:

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");

// Some samples to try
let strings = ["Hello", "98052", "101"];

// Validators to use
let validator = new zip();

// Show whether each string passed each validator
strings.forEach(s => {
  console.log(`"${ s }" - ${ validator.isAcceptable(s) ? "matches" : "does not match" }`);
});

export as namespace 表单创建了一个全局变量,因此无需导入即可使用它,但您仍可以使用import { name } from "some-library" 导入表单来导入它。请参阅给出此示例的documentation

数学库.d.ts

export const isPrime(x: number): boolean;
export as namespace mathLib;

然后可以将库用作模块中的导入:

import { isPrime } from "math-lib";
isPrime(2);
mathLib.isPrime(2); // ERROR: can't use the global definition from inside a module

它也可以用作全局变量,但只能在脚本内部使用。 (脚本是没有导入或导出的文件。)

mathLib.isPrime(2);

这里有一个泛型类型库,它不知道正在使用哪个模块系统,因此它试图覆盖所有基础。

【讨论】:

  • 谢谢邓肯。在发布之前,我已经阅读了这两个示例。我仍然不确定“但您仍然可以使用 import { name } from "some-library" 导入形式导入它”的含义。在这个例子中name 是什么?具体来说,当export =export as namespace 一起使用时,import from 样式导入的含义是什么?
  • @Duncan,如何扩展 mathLib 命名空间,同时将其保持在全局范围内(无模块扩充)
  • @AlexandruC,不知道。将其作为一个单独的问题发布?
  • @AlexandruC 链接已损坏
猜你喜欢
  • 2021-04-10
  • 2018-11-29
  • 1970-01-01
  • 2017-01-09
  • 1970-01-01
  • 2022-12-02
  • 2021-05-26
  • 1970-01-01
  • 2013-12-02
相关资源
最近更新 更多