'Node js require code instead of file
I am trying to setup an interface, where I can write one js file that can be used on the server (nodejs) and on the client (javascript).
An example file would be a Vector object, that I would like to use on both the client and the server, as I am creating a multiplayer game.
In node.js, I know that you can use the following syntax to require source files...
var Vector = require('./vector');
Then you can access its module.exports
by typing in Vector
.
The problem here is that for the server I need an extra bit of code at the end of the file...
module.exports = Vector;
... which is not necessary on the client.
Is it possible to maybe require source code, something like the following?
var data = (...) // get data from vector.js file
var Vector = require_code(data + 'module.exports = Vector');
If not, there might be another way of doing what I am trying to accomplish.
That might sound a little confusing, but help is greatly appreciated!
Thanks in advance,
David.
Solution 1:[1]
Sounds like you are looking for UMDs - Universal Module Definitions.
(function (root, factory) {
if (typeof define === "function" && define.amd) {
define(["jquery", "underscore"], factory);
} else if (typeof exports === "object") {
module.exports = factory(require("jquery"), require("underscore"));
} else {
root.Requester = factory(root.$, root._);
}
}(this, function ($, _) {
// this is where I defined my module implementation
var Requester = { // ... };
return Requester;
}));
You'll need to change the name in root.Requestor
to be the name of your module. root
picks up the value of this
which will be the global object or what you normally call window
on the browser.
This particular example looks for jQuery
and underscore
as example dependencies, but they are easy enough to factor out if you need.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jeremy J Starcher |