【问题标题】:calling function with alias declared in other module in TypeScript在 TypeScript 的其他模块中声明的别名调用函数
【发布时间】:2017-11-08 15:13:10
【问题描述】:

这是Angular node_modulesuuid文件夹内v4.js文件的内容:

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;

我是用这个语句来导入函数的:

import { v4 as uuid } from 'uuid';

令我惊讶的是,调用 v4 函数有两种方式:

我可以使用:

uuid.v4();

或者干脆

uuid();

uuid() 怎么还调用 v4 函数?

【问题讨论】:

  • 您可以同时调用它,因为别名在技术上 函数 v4,同时别名也具有对所有模块导出函数的函数引用.
  • 好吧,如果只是这样,它看起来就像一个全局函数(文件不是匿名函数)。也许这解释了它?可以肯定的是,请尝试在您的 Chrome 控制台中调用 v4 函数,如果它弹出,那么它是全局的。

标签: javascript angular typescript import


【解决方案1】:

该行为并非特定于 TypeScript。这是因为这个包中的the way the export works

由于在 CommonJS 模块中没有区分 default 和 * 导出,命名导出通常作为 module.exports 的属性导出。 v4 目前是默认导出,这可能会在未来的软件包版本中发生变化:

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

【讨论】:

  • 感谢您的光临! * 出口究竟是什么?我发现我对这些软件包的工作原理知之甚少。例如,我不知道 index.js 在这里做什么。我到底应该用谷歌来教育自己什么?
  • 请参阅 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 获取 *。 *default 在 ES6 模块中是不同的东西,但在 CommonJS 模块中是相同的东西。你可以在这里查看更多关于 CJS 模块的信息 nodejs.org/docs/latest/api/modules.html ,或者可能是“CommonJS vs ES6”文章之一。希望这能回答你的问题。 v4 本身只是一个方法,所以也可以使用v4.v4.v4()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-12
相关资源
最近更新 更多