I'm trying to work with a CommonJs module which exports a variable conditionally based on whether module
and module.exports
are undefined. The issue I'm currently having is that sometimes when I use import { something } from 'themodule'
it gives me undefined something
. While looking into the source code, I found the following export conditions:
if (typeof module !== 'undefined' && module.exports) {
module.exports = Prism;
}
So I added some logs to the file to see whether the condition is satisfied or not via:
console.log('module: ', module, 'module.exports: ', module.exports)
if (typeof module !== 'undefined' && module.exports) {
console.log('module.exports!')
module.exports = Prism;
}
Which however gives me strange output:
module: { exports: [Getter/Setter] } module.exports: undefined
As you can see, the module
log seem to indicate it has an exports
property however when log module.exports
separately, it says it's undefined. How is this possible ? Can someone help understand why this check is needed and why sometimes module.exports
can be undefined ? Thanks!
CodePudding user response:
There are a few mostly-unrelated issues here.
The issue I'm currently having is that sometimes when I use import { something } from 'themodule' it gives me undefined something
This can occur if you have a circular dependency in your import
chain. If a.js imports from b.js, and b.js imports from c.js, and c.js imports from a.js - then, for code running at the top level of those modules, there's no guarantee that code running at the top level of other modules has been executed. While you can experiment and see what's going on, a better approach would be to
- remove the circular dependency, and/or
- have only a single entry point in your code, from which everything else meaningful is called, so that circular dependencies downstream don't cause issues - have your downstream exports be functions, without top-level code that depends on other imports.
Which however gives me strange output:
module: { exports: [Getter/Setter] } module.exports: undefined
This means that:
- The
exports
property is a getter/setter - When you invoked the getter, it apparently returned
undefined
. The property exists, but invoking the getter doesn't return anything. Eg
const obj = {
get prop() {
}
};
console.log(obj.hasOwnProperty('prop'));
console.log(obj.prop);
Can someone help understand why this check is needed
The check of
if (typeof module !== 'undefined' && module.exports) {
is simply to check to see if the code is being executed in the CommonJS context, and if it is, it assigns the Prism
to the exports.