sanjihan
sanjihan

Reputation: 6014

calling function with alias declared in other module in TypeScript

This is the content of v4.js file inside uuid folder in Angular node_modules:

var rng = require('./lib/rng');
var bytesToUuid = require('./lib/bytesToUuid');

function v4(options, buf, offset) {
  var i = buf && offset || 0;

  if (typeof(options) == 'string') {
    buf = options == 'binary' ? new Array(16) : null;
    options = null;
  }
  options = options || {};

  var rnds = options.random || (options.rng || rng)();

  // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  rnds[6] = (rnds[6] & 0x0f) | 0x40;
  rnds[8] = (rnds[8] & 0x3f) | 0x80;

  // Copy bytes to buffer, if provided
  if (buf) {
    for (var ii = 0; ii < 16; ++ii) {
      buf[i + ii] = rnds[ii];
    }
  }

  return buf || bytesToUuid(rnds);
}

module.exports = v4;

I am using this statement to import the function:

import { v4 as uuid } from 'uuid';

To my surprise, there are 2 ways of calling v4 function:

I can use:

uuid.v4();

or simply

uuid();

How come uuid() still calls v4 function?

Upvotes: 1

Views: 365

Answers (1)

Estus Flask
Estus Flask

Reputation: 222498

The behaviour isn't specific to TypeScript. This happens because of the way the export works in this package.

Since default and * exports aren't distinguished in CommonJS modules, named exports are commonly exported as properties of module.exports. v4 is currently a default export, and this will possibly change in future package versions:

const uuid = require('uuid');
uuid === uuid.v4;

Upvotes: 1

Related Questions