使用 browserify 创建通用函数

Create a common function with browserify

我是 Browserify 的新手,我有不止一个在不同文件中使用的功能。我正在重构我的代码以将这个函数提取到一个文件中,所以我必须为这些函数维护这个源代码。 这些函数已经在我的其他文件中使用,所以我不想改变我调用它们的方式,所以如果我以这种方式使用函数

var x= foo();

不想将消费者javascript更改为

var x= lib.foo();

我创建了一个文件“./lib/common.js”

module.exports.trump = function (str, pattern) {
      var trumped = "";  // default return for invalid string and pattern

      if (str && str.length) {
        trumped = str;
        if (pattern && pattern.length) {
          var idx = str.indexOf(pattern);

          if (idx != -1) {
            trumped = str.substring(0, idx);
          }
        }
      }
      return (trumped);
        }

module.export.foo = function(options){
  return 1;
}

在我的 app.js 中我有:

require('./lib/common.js')
trump(ui.item.PlaceId, "-sky" )

浏览我的 app.js 文件后(没有错误)我在我的浏览器应用程序中使用它,但我得到 Uncaught ReferenceError: trump is not defined

我应该如何使用单个 common.js 文件导出我的函数,以便在像 foo(); 这样简单地调用它们时使它们工作?

要求您的图书馆后:

var common = require('./lib/common.js');

您可以使用以下方法将其合并到 this 中:

  1. jQuery 扩展()

    $.extend(this, common);
    
  2. Underscore.js 扩展()

    _.extend(this, common);
    
  3. Object.assign() - ECMAScript 2015 (ES6) 标准 - 检查浏览器兼容性

    Object.assign(this, common)
    
  4. 一个Object.assign polyfill(来自https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign):

    if (!Object.assign) {
        Object.defineProperty(Object, 'assign', {
            enumerable: false,
            configurable: true,
            writable: true,
            value: function(target) {
                'use strict';
                if (target === undefined || target === null) {
                    throw new TypeError('Cannot convert first argument to object');
                }
    
                var to = Object(target);
                for (var i = 1; i < arguments.length; i++) {
                    var nextSource = arguments[i];
                    if (nextSource === undefined || nextSource === null) {
                        continue;
                    }
                    nextSource = Object(nextSource);
    
                    var keysArray = Object.keys(nextSource);
                    for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
                        var nextKey = keysArray[nextIndex];
                        var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
                        if (desc !== undefined && desc.enumerable) {
                            to[nextKey] = nextSource[nextKey];
                        }
                    }
                }
                return to;
            }
        });
    }