EzDevInfo.com

umd

UMD (Universal Module Definition) patterns for JavaScript modules that work everywhere.

How does browserify bundle a universal module

I know browserify can consume UMD modules by means of transforms, but when I want to build a lib using browserify, how can I build an UMD module? Is there any transform I can use?


Source: (StackOverflow)

How to use requirejs to load jQuery plugin intlTelInput?

The plugin in question is https://github.com/Bluefieldscom/intl-tel-input. All script tags are inserted by requirejs properly, but I still can't use the plugin intlTelInput.

What am I missing?

require.config({
    baseUrl: "/Scripts/require",
    paths: {
        "jquery": "/Scripts/jquery-2.1.3.min",
        // jquery plugins
        "intlTelInput": "/Scripts/jquery/plugin/intlTelInput-5.3.0.min"
    }
});

define(["jquery", "intlTelInput"], function ($, tel) {
    console.log(tel); // output: undefined
});

Source: (StackOverflow)

Advertisements

JQuery library module export

I am trying to understand how jQuery sets itself up.

Right at the beginning jQuery automatically calls a function, which exports a module.

How does the setup work?

Here some more detailed sub-questions which might answer the the more general question:

  • What is the use of the recursive call to function(w) at module.exports?
  • What is the use of the noGlobal variable?
  • Where is the factory actually set up and what is its type?
  • Why can the factory argument get called with one argument and with two as well?
  • What is the global argument supposed to contain? (I wish there were a type like in c++...)

(function( global, factory ) {

    if ( typeof module === "object" && typeof module.exports === "object" ) {
        // For CommonJS and CommonJS-like environments where a proper `window`
        // is present, execute the factory and get jQuery.
        // For environments that do not have a `window` with a `document`
        // (such as Node.js), expose a factory as module.exports.
        // This accentuates the need for the creation of a real `window`.
        // e.g. var jQuery = require("jquery")(window);
        // See ticket #14549 for more info.
        module.exports = global.document ?
            factory( global, true ) :
            function( w ) {
                if ( !w.document ) {
                    throw new Error( "jQuery requires a window with a document" );
                }
                return factory( w );
            };
    } else {
        factory( global );
    }

    // Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {

Source: (StackOverflow)

Browserify with deamdify transform OR UMD, a few AMD modules have dependencies on other AMD modules

We have a site that is for the most part written in modules using the CommonJS/node.js module format. There is a need to also use a handful of modules that are written in RequireJS/AMD. Some of those modules do have a dependency on one or a couple of other RequireJS/AMD modules.

For example, here is a RequireJS/AMD module:

define(['jquery', 'harvey'], function ($, Harvey) {
  //...module does stuff with $ and Harvey
});

Now if 'jquery' and 'harvey' need to be resolved while using browserify with a deamdify transform, how can we do that?


Source: (StackOverflow)

Is it reasonable to use UMD with no exports, to simply augment a dependency?

I'm creating my first AngularJS module intended for open source distribution. I'd like to package it in a way that's easy for others to consume.

The UMD project provides a pattern for exporting JavaScript modules that are compatible with AMD, CommonJS (or at least Node) and browser globals:

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define(['b'], factory); // AMD
  } else if (typeof exports === 'object') {
    module.exports = factory(require('b')); // Node
  } else {
    root.returnExports = factory(root.b); // browser global (root is window)
  }
}(this, function (b) {
  // use b in some fashion
  return {}; // return a value to define the module export
}));

However, since AngularJS has its own internal module system, registering a module is done by simply calling a method on the angular object, i.e. angular.module(). Thus, a UMD module wouldn't need to export anything; it would just need to require and act on angular. In terms of the previous example, I think that would look something like this:

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    factory(require(['b'])); // AMD
  } else if (typeof exports === 'object') {
    factory(require('b')); // Node
  } else {
    factory(root.b); // browser global (root is window)
  }
}(this, function (b) {
  // use b in some fashion
}));

Or, specific to my case:

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    factory(require(['angular'])); // AMD
  } else if (typeof exports === 'object') {
    factory(require('angular')); // Node
  } else {
    factory(root.angular); // browser global (root is window)
  }
}(this, function (angular) {
  angular.module( ... );
}));

Is this no big deal, or does it go against the spirit of UMD? I ask because I couldn't find any UMD patterns that don't export anything.


Source: (StackOverflow)

How can I define just a single object constructor with UMD?

I'm defining a module with the UMD style of defining a module that can be used across CommonJS, AMD, and browser globals like so:

(function (root, factory) {
    if (typeof define === 'function' && define.amd) define(['exports'], factory);
    else if (typeof exports === 'object') factory(exports);
    else factory(root.GlobalObject = {});
})(this, function (exports) {
    // Module definition here
});

This is great for if I want to attach properties to the exported object, but what if I want to just return a single constructor function from this definition and have all three systems able to load up this module and directly use the function returned, rather than having to return an object literal and access the constructor as a property of the literal?


Source: (StackOverflow)

UMD javascript module which also works in strict mode

I'm having trouble rewriting this to work in 'strict' mode. Since 'this' is not defined explicitly I'm getting jshint errors on compile. I'm thinking my brain is just not thinking abstractly enough to find a creative solution. Any help would be appreciated. Code adapted from the Universal Module Definition Github repo: https://github.com/umdjs/umd/blob/master/returnExports.js

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
    // AMD Module
        define([], factory);
    } else if (typeof module === 'object' && module.exports) {
    // Node Module
        module.exports = factory();
    } else {
    // Browser Global
        root.returnExports = factory();
  }
}(this, function () {
    return {};
}));

Source: (StackOverflow)

Universal module definition - writing style

It took me a long time to understand this pattern at first, and I think it is mostly because of the way that it is written:

(function(root, factory) {
    // Export MyModule depending on the environment
    if (typeof define === "function" && define.amd) {
        define("MyModule", [], factory);
    } else {
        root.MyModule = factory();
    }
}(this, function() {
    return { 
        // Module definition
    };
}));

Isn't that the exact same thing as this?

(function(root) {
    var factory = function() {
        return { 
            // Module definition
        };
    };
    // Export MyModule depending on the environment
    if (typeof define === "function" && define.amd) {
        define("MyModule", [], factory);
    } else {
        root.MyModule = factory();
    }
}(this));

There is a var statement now, but I find this much easier to read. Am I missing something here? Is there a good reason to use the first approach?


Source: (StackOverflow)

UMD style submodules

Is it possible to seperately create submodules in an UMD style fashion? Say I have this:

(function (root, factory) {
	if ( typeof define === 'function' && define.amd ) {
		define([], factory(root));
	} else if ( typeof exports === 'object' ) {
		module.exports = factory(root);
	} else {
		root.thing = factory(root);
	}
})(typeof global !== 'undefined' ? global : this.window || this.global, function (root) {

	'use strict';

	// Object for public APIs
	var thing = {};
	thing.add = function(number) {
        return number + 2;
    };
    
    return thing;
    

});

What would be the best way to build up thing.sub object in a seperate file? I would like to keep my dev env clean by seperating modules this way...


Source: (StackOverflow)

UMD from Spyder doesn't reload my module

I am currently developing some simple modules for data analysis. Take the following example:

from __future__ import division, print_function, absolute_import
import pharmacotoxic as pht
#reload(pht)

conditions= ['c1','c2','c3','c4','c5']
pht.make_master_file('completeData', datapath, conditions)

Which calls pht as a module. For now, my module simply says:

import pandas as pd
import numpy as np
import os
def make_master_file(mastername, path, conditions, wells= 3, f1= 'dates.txt'):        
    print('hello world')

But if I make a change to the pht module, print('bye world') for example, instead of the current print command, spyder doesn't automatically update the module unless I explicitly add a reload command.

I also don't get a message saying UMD has reloaded my modules, so I assume it isn't working.

Could anyone point me towards an answer?

All scripts are in the same directory and in theory the UMD is on.


Source: (StackOverflow)

Browserify universal module definition - browser/node different dependencies

How is it best to setup my UMD to inject different dependencies based on if its being run in a node or a browser environment?

I have the following UMD for my module which should work in both browser and node environments. I am struggling however because Node requires both the 'ws' and 'atob' dependencies whereas the browser doesn't.

Normally, the third condition would run here, but because I am using Browserify, the second condition is met...and the un-required dependencies are fetched.

(function (root, factory) {

    if (typeof define === 'function' && define.amd) {

        // AMD
        define(['q'], ['ws'], ['atob'], factory);

    } else if (typeof exports === 'object') {

        // Node OR Browserify
        module.exports = factory(require('q'), require('ws'), require('atob'));


    } else {

        // Browser globals (root is window) Q and WebSocket is already available
        root.returnExports = factory(root.Q, root.WebSocket, root.atob);

    }
}(this, function (Q, WebSocket, atob) {


     return {
         //stuff
     };

}));

Is it possible for Browserify to run the module definition as if it were a browser? In which case, I could use..

 typeof window === 'undefined'

Source: (StackOverflow)