Skip to content

Instantly share code, notes, and snippets.

@epoberezkin
Last active February 11, 2024 22:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save epoberezkin/5020250 to your computer and use it in GitHub Desktop.
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).
// 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;
});
All modules templates I've seen were not suited for code sharing
between client/server in case the module has dependencies.
This template will only work on server-side if module's dependencies
are in node_modules (installed with npm) on server side and are
available without any path in require.
In case the dependencies are part of the application, their paths
will be different in nodejs and in browser,
so some adaptation will be required to use correct dependencies paths.
It's easy to update this template to add global browser environment
(I didn't need it) and application modules with paths (not installed with npm).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment