Reputation: 25778
I am reading some other's code, I saw a piece of code like this
if ( typeof module === 'object' ) {
module.exports = BBB;
}
I am wondering 1) why using if statement here 2) when using module.exports, does it mean all BBB namespace is exported
BTW, BBB is a namespace defined like
var BBB = {};
Upvotes: 0
Views: 57
Reputation: 2214
Most likely the author is creating a module that may not necessarily be consumed in a CommonJS enviorment, but still is offering support for it.
The CommonJS standard defines a few free variables, require
, exports
, and module
. module
must be an Object.
So when the author is checking that module
is of type object
, they are essentialy checking for CommonJS support, they are then assigning module.exports
to BBB
, so that when a consumer require
's their module BBB
is returned. I won't go into the details of CommonJS but you can check out the standard for more info.
Why would I check for CommonJS support?
Because your code is intended for use in multiple enviornments/packagers. For example Browserify, and Webpack use the CommonJS standard to package code for use in the browser. But when creating an API for the browser, one should assume that consumers may not be using CommonJS, therefore module
will not be defined and assigning a value to module.exports
will throw an error.
Upvotes: 1
Reputation: 135415
It's likely the module is intended to work in both the browser and on the server side (presumably using node.js).
Creating a sort of wrapper for your module allows it to be used in a variety of javascript loaders such as AMD or RequireJS or CommonJS (used by node)
I'd also recommend looking at umdjs/umd (Universal Module Definition). This repo documents how you can create a wrapper for your module so that it will work in every environment you target.
Lastly, you can sort of think of module.exports
like a return value of a function. When someone imports the module, the export is what is given to them.
If this is used
// bbb.js
module.exports = BBB;
When the module is required using (for example)
// otherfile.js
var BBB = require('./bbb');
BBB
will match the exported object.
Check out the node.js module docs for more general help.
Upvotes: 1
Reputation: 408
1) This checks if you are using this code on the server side (NodeJS).
2) Yes, all BBB namespace is exported
Here are all necessary information: http://www.sitepoint.com/understanding-module-exports-exports-node-js/
Upvotes: 0
Reputation: 311
it is to detect what environment you are in, module exists in node, but not in the browser without browserify or the like
Upvotes: 1