【问题标题】:module.exports cannot be set when passed in as argumentmodule.exports 作为参数传入时无法设置
【发布时间】:2016-06-18 11:14:58
【问题描述】:

我正在使用 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);

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

【问题讨论】:

  • 为什么不简单地返回 Service 并从 iife 的结果中分配 exports

标签: javascript browserify commonjs


【解决方案1】:

在您的第一个示例中,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 指向同一个对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 2021-07-29
    相关资源
    最近更新 更多