UMD:正在分配给模块,导出冗余

UMD: is assigning to module.exports redundant?

本文关键字:冗余 模块 分配 UMD      更新时间:2023-09-26

我看到JS库使用这两种不同的实现。唯一的区别是 CommonJS 行。

它们在功能上是否相同?是否不需要将值分配给模块导出?

/* 1: Assignment to module.exports */
(function(factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD
    define(['jquery'], factory);
  } else if (typeof module === 'object' && module.exports) {
    // CommonJS
    module.exports = factory(require('jquery'));
  } else {
    // Browser globals
    factory(jQuery);
  }
}(function($) {
  $.fn.jqueryPlugin = function () { return true; };
}));
/* 2: Doesn't assign to module.exports */
(function(factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD
    define(['jquery'], factory);
  } else if (typeof module === 'object' && module.exports) {
    // CommonJS
    factory(require('jquery'));
  } else {
    // Browser globals
    factory(jQuery);
  }
}(function($) {
  $.fn.jqueryPlugin = function () { return true; };
}));

tl;dr 这并不重要,但通常建议包括module.exports = ...

更长的解释

我相信您显示的代码中的"更好"版本是设置module.exports的版本:

module.exports = factory(require('jquery'));

但是,它不必如此。一般来说,你使用 jQuery-plugin 的方式是通过全局 $/jQuery 变量,在这种情况下不需要module.exports = ...。使jQuery插件工作的行是:

$.fn.jqueryPlugin = function () { return true; };

但是 - 原则上 - 你可以像这样使用插件,直接调用它而不通过jQuery:

myjQueryPlugin = require('myjQueryPlugin');
var $myElement = $('#my-element');
myjQueryPlugin.apply($myElement, {});

在这种情况下,您需要设置 module.exports .请注意,这看起来确实有点奇怪,所以一般来说,大多数人不会像这样使用你的插件。

通过设置module.exports,您可以支持这两种用例,而不会丢失任何内容。

另请参阅:http://blog.npmjs.org/post/112712169830/making-your-jquery-plugin-work-better-with-npm(将插件导出为模块(可选)部分)