简体   繁体   中英

What does `export as namespace` mean in a TypeScript .d.ts file?

I've been reading some declaration files on DefinitelyTyped and have often come across files like this:

declare function domready(callback: () => any) : void;

export = domready;
export as namespace domready;

I understand the first two lines - declare a function and export that function as the module object. But what is the last line? Do I need this in my declaration file? What does it do?

This is a UMD module declaration .

If you're not familiar already, UMD is a creation pattern that allows the same JavaScript library to be used as a global variable (one that can be accessed anywhere) or as a module (one that is specifically loaded at runtime) depending on the environment.

Many libraries are written with the UMD pattern. For example, you may write

moment.parse("12-31-2017")

in the browser, but write code like this in node.js:

const m = require("moment");
m.parse("12-31-2017")

When you write an export declaration like export function parse , TypeScript knows you're describing a module like in the second block of code. But if the library you're writing a .d.ts file for also creates a global variable, you can describe that global variable using the UMD module declaration syntax:

export as namespace the_global_identifier;

Some UMD libraries will always create a global, whereas others must be imported if they are loaded in an environment where a module system is present. In general libraries do not clearly document which behavior they use, which means declaration file authors don't really know which to expect, which means TypeScript is conservative and will only allow access to the global identifier if the file referencing it is not a module.

If you're writing a declaration file and aren't sure if they library is UMD or not, check for patterns that look like this:

(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ?     factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  (factory((global.mymodule = global.mymodule || {})));
}(this, function (exports) { 'use strict';
    function myFunction() {
        console.log('hello world');
    }
}));

This is the tell-tale UMD smell: lots of typeof checking for "exports", "module", and "define" followed by an assignment to an "exports" parameter given to a big function body. If you don't see this in the library code, it's almost certainly not a UMD module and you should not write an export as namespace declaration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM