javascript - 作为参数传入时无法设置 module.exports

标签 javascript browserify commonjs

我正在使用 Browserify 构建我的包.

我有以下 service.js:

(function (exports, require) {

     // ...
     var Service = function (name, region) {
         this.name = name;
         this.region = region;
         // ...
     }

     exports = Service;

})(module.exports, require);

每当我尝试在另一个模块上require('./service') 时,我都会得到一个空对象,就好像从未设置过exports 对象一样。

如果我在没有参数封装的情况下使用 module.exports,一切正常:

(function (require) {

   // ...
     var Service = function (name, region) {
         this.name = name;
         this.region = region;
         // ...
     }

     module.exports = Service;

})(require);

为什么会发生这种情况以及为什么需要这样做?

最佳答案

在您的第一个示例中,example 是匿名函数范围内的变量,它指向 module.exports。当您说 exports = Service 时,您正在更改 exports 指向的内容,而不是 module.exports 指向。

当您说 module.exports = Service 时,您正在更改 module 的属性,该属性是全局范围的。

补充说明:

(function (m, require) {

    // ...
    var Service = function (name, region) {
        this.name = name;
        this.region = region;
        // ...
    }

    m.exports = Service;

})(module, require);

m 指向 module,当我们设置 m.exports 时,我们正在设置 module.exports,因为 mmodule 指向同一个对象。

关于javascript - 作为参数传入时无法设置 module.exports,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35800802/

相关文章:

javascript - 通知工厂模型内部更改后,Angular ng-repeat 不更新

javascript - f :ajax onerror called before listener

javascript - 根据 Rails/React 应用程序上 api 调用的状态更新我的 View

javascript - 三.js TypeError : 'global' is undefined in Firefox

javascript - 在 Nowjs 中传递带有回调参数的对象

browserify - 如何在浏览器中获取依赖树?

jquery - 加载 JqueryUI 的 Browserify 无法正常工作

node.js - 克服 Node 和 browserify 路径解析中的差异

javascript - 在 Node-Gulp-Webpack 构建中包含外部 JavaScript 文件

javascript - 我可以在 NodeJS 的 require 函数中使用别名吗?