Last active
January 21, 2016 03:10
-
-
Save thurt/34087583a3caf1405e9c to your computer and use it in GitHub Desktop.
node/browser capable module check
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
var Validator = (function() { | |
var Validator = function(options) { | |
... | |
}; | |
Validator.prototype.foo = function foo() { | |
... | |
}; | |
return Validator; | |
})(); | |
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') | |
module.exports = Validator; | |
else | |
window.Validator = Validator; | |
})(); |
If a project goes beyond a few script tags, then I think the best alternative is to use browserify instead of script tags.
browserify will create a functioning "local module system" within a javascript file which can bundle all the individual scripts. While there is some overhead to add the local module system into the javascript, it is worth it in terms simplifying deployment and reducing the number of HTTP requests (usually means a faster loading web page).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: This last solution is less verbose than example 1, but it is also less ideal in a Node run-time because
this === global
--meaning that we are blindly putting all objects in global scope (greater potential for unintended name collision).In the first example, we are putting the object on
module.exports
, which will be in a local variable of the calling module.As for a browser environment, all of these possibilities will blindly be adding to the window (global scope).