What I'm trying to do is adapt my jQuery-plugin to work with jQuery on Node.js.
From what I understand, CommonJS in it's most basic form requires a library to be wrapped in a closure, and that closure should be made available as a parameter of an 'exports' parameter. That way, the code is neatly contained in its own namespace (via a named variable) and doesn't pollute the global namespace.
jQuery itself should fall under the '$' namespace.
Ala:
var $ = require(jquery);
But my plugin should also fit under the '$' namespace.
Plugin code:
(function( $ ) {
// plugin code goes here
})(jquery);
exports.jquery = jquery // will this work?
Ex:
var $ = require(jquery);
$ = require(jquery-csv.js); // will this work?
To work in the browser, everything is setup to be callable from the '$' namespace even though my modules are setup as a sub-namespace of '$' (ie '$.csv').
Is there a standard way to do multiple requires on a single namespace? If not, there a viable alternative (ex doing a shallow copy on the plugin code)?
Note: The anonymous function wrapper follows the standard jquery guidelines.
Note: This fix will be applied to the jquery-csv plugin.
You should require jQuery inside your plugin:
var $ = require("jquery");
This is also the technique in UMD (Universal Module Definition), a standard for both CommonJS and AMD.
Also see the example for a jQuery plugin with UMD
Easiest way I can think of doing something like this would be doing something like the following:
var $ = require("jquery");
require("jquery-csv")($);
That also means you can just do something like this:
module.exports = exports = function (jquery) {
//You modify the jquery object here.
};
Modification of the $ object should be done in accordance to jQuery plugins recommendations. I will believe you are already aware of them for what you said.
I'm sure someone will come up with a smarter way :) but this should work for now. You could also just return a modified jquery object and then assign it to the $ object on the scope in which you originally included the module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With