I'm using RequireJS, and trying to pack up a jQuery widget for easy usage into one file. Inside the widget's JavaScript code are a certain number of non-UI functions that don't call $
-anything, that I'd like to export and be able to use on the server side.
(The shared routines that don't depend on jQuery used to be in a separate module called client-server-common.js. But like I said, I'm looking to reduce the number of files...and there's no real reason to be hung up on including the dead code for the widget on the server. So the widget can just subsume the common code.)
I'd like my only dependencies for the widget to be jQuery and underscore, with jQuery optional (and it degrades into what was client-server-common.js in that case). So the interface I'm looking for would be like:
require(['jquery', 'underscore'], function ($, _) {
var exports = {...};
if ($) {
// Do the stuff that only makes sense in the client
// Totally fine if there is no jquery; in that case
// all we probably care about are the exports
...
}
// Do the stuff for both client and server
...
// Return the exported functions
return exports;
}
Reading up on what others have asked, I notice this answer to this question from January says "You cannot really set it optional":
That's not what I want. Is that the last word? :-/
It seems that I can get around this by installing the jquery NPM package, which apparently does stuff with the DOM somehow:
Can I use jQuery with Node.js?
My understanding would be that if I added this dependency and just ignored it, I'd be okay. I might even find that there was some good reason to do DOM manipulation on the server (I haven't thought enough to figure out why or how that would be useful, is it?)
So should I add the dependency for simplicity's sake, and just not use it? Or can I rig it up so that I just give a jQuery of null
on the server configuration, through some magic that doesn't involve waiting for timeouts and errors and hacks? Could someone make a "jquery-null" package that somehow just came back and gave you a {}
or null for jQuery to smooth over situations like this?
Advice appreciated! :-/