Last active
February 11, 2024 22:55
-
-
Save epoberezkin/5020250 to your computer and use it in GitHub Desktop.
Javascript module template to share code between Node (CommonJS) and browser with requirejs (AMD).
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
// checking environment, if it is not AMD, emulate define for Node | |
if (typeof define !== 'function' || ! define.amd) | |
var define = function(moduleName, requirements, func) { | |
var dependencies = []; | |
requirements.forEach(function(req) { dependencies.push( require(req) ); }); | |
func.apply(this, dependencies); | |
}; | |
// dependencies are optional, in case there are no dependencies an empty array should be used | |
// but the second parameter should be array as no type checking is made in function define | |
// !!! | |
// moduleName parameter is needed to have the module working after require optimizer | |
// moduleName should have the same "path" you use in require (which is not a real path), | |
// node just ignores it | |
define('myModule' /* or 'app/myModule' - see comment above */, | |
['dep1' /* , more required dependencies */ ], | |
function(dep1 /*, dependencies variables */) | |
{ | |
var myModule = {}; // or = function(...) {...} | |
// exports for Node | |
if (typeof module !== 'undefined' && module.exports) | |
module.exports = myModule; | |
// | |
// module code | |
// | |
// exports for AMD (requirejs) | |
return myModule; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment