jquery.ns-autogrow icon indicating copy to clipboard operation
jquery.ns-autogrow copied to clipboard

AMD/UMD wrap-IIFE

Open ctrlmaniac opened this issue 8 years ago • 2 comments

Please, can you change the old jquery IIFE to the one provided by umdjs?

I dont' know coffeescript, otherwise I'd pull a request.

// Uses CommonJS, AMD or browser globals to create a jQuery plugin.

(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof module === 'object' && module.exports) {
        // Node/CommonJS
        module.exports = function( root, jQuery ) {
            if ( jQuery === undefined ) {
                // require('jQuery') returns a factory that requires window to
                // build a jQuery instance, we normalize how we use modules
                // that require this pattern but the window provided is a noop
                // if it's defined (how jquery works)
                if ( typeof window !== 'undefined' ) {
                    jQuery = require('jquery');
                }
                else {
                    jQuery = require('jquery')(root);
                }
            }
            factory(jQuery);
            return jQuery;
        };
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {
    $.fn.jqueryPlugin = function () { return true; };
}));

ctrlmaniac avatar Dec 05 '16 23:12 ctrlmaniac

I probably can, can you please explain why? Thx

ro31337 avatar Dec 06 '16 00:12 ro31337

So I can use it in a node environment without having to shim it, or use an other package to make it compatible!

It's now a common practice for jquery plugins to use this IIFE instead of the one provided by the jquery team on their blog, to make jquery plugins node-compatibles. You can check on the npm's blog!!

Jquery itself it's built inside this IIFE, so I guess that it's time to change and upgrade.

The core functionality won't change and you will still be able to use it like before (src in a script tag). But with this IIFE I can use it (in a simpler way - requiring it) with Browserify or Webpack without shimming it!

So to sum up:

  • extends usage to AMD and universal modules (es6), thus node and more envs to come in the future thanks to es6.
  • use with tools like browserify and webpack without shimming it.
  • it's now a common practice to do it
  • jquery itself is wrapped inside this IIFE

I hope these are enough reasons!!

ctrlmaniac avatar Dec 06 '16 00:12 ctrlmaniac