【发布时间】:2022-01-01 03:37:18
【问题描述】:
我正在尝试使用 CommonJs 模块,该模块根据 module 和 module.exports 是否未定义有条件地导出变量。我目前遇到的问题是,有时当我使用import { something } from 'themodule' 时,它会给我未定义的something。在查看源代码时,我发现了以下导出条件:
if (typeof module !== 'undefined' && module.exports) {
module.exports = Prism;
}
所以我在文件中添加了一些日志,以查看是否满足条件:
console.log('module: ', module, 'module.exports: ', module.exports)
if (typeof module !== 'undefined' && module.exports) {
console.log('module.exports!')
module.exports = Prism;
}
然而这给了我奇怪的输出:
模块:{ 出口:[Getter/Setter] } module.exports:未定义
如您所见,module 日志似乎表明它具有 exports 属性,但是当单独记录 module.exports 时,它表示它是未定义的。这怎么可能 ?有人可以帮助理解为什么需要此检查以及为什么有时 module.exports 可以未定义?谢谢!
【问题讨论】:
-
这个输出没有什么奇怪的。
console.log({ get exports(){ return undefined; }, set exports(_){} });记录同样的事情。该属性是一个getter / setter。使用module.exports你调用 getter;它返回undefined。 拥有一个属性和未定义的属性是两个不同的东西。module.hasOwnProperty("exports")检查属性是否存在;module.exports改为检查真实性。 “为什么有时module.exports可能是未定义的” —obj.x在const obj = { x: undefined };中是undefined。 -
@SebastianSimon 太棒了。这就说得通了。但是无论如何,您知道为什么在导出变量时需要进行这样的检查吗?
标签: javascript node.js commonjs ecmascript-next