【问题标题】:How to use both default export and normal exports in RequireJS?如何在 RequireJS 中同时使用默认导出和正常导出?
【发布时间】:2021-03-07 18:58:28
【问题描述】:

lib.js

exports.value = 'Some value'

module.exports = {
  libraryName: '@CoolLibrary'
}

ma​​in.js

const { value } = require('./lib')
console.log('Value is '.concat(value))

当我编写上面的代码时,看到输出为Value is undefined。但是,我已在库中将value 导出为Some value

好像我错过了什么。

在 Node.js 中同时使用 module.exportsexport.[value] 导出的正确方法是什么?

【问题讨论】:

标签: javascript node.js commonjs


【解决方案1】:

exportsmodule.exports 的别名,所以当你这样做时

module.exports = {
  libraryName: '@CoolLibrary'
}

您完全替换了刚刚分配value 的对象,使value 不可用。

这是不替换 exports 对象的一个​​很好的理由;相反,只需添加:

exports.value = 'Some value';
exports.libraryName = '@CoolLibrary';

或者如果你喜欢:

Object.assign(exports, {
    value: 'Some value',
    libraryName: '@CoolLibrary'
});

【讨论】:

    猜你喜欢
    • 2016-08-20
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 2017-02-01
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    • 2016-06-28
    相关资源
    最近更新 更多