Search code examples
javascriptrequirejsjs-amdlibphonenumber

convert a javascript library to AMD


I'm trying to use a library -- Google's libphonenumber -- in my require application that is not AMD. What is the best way to consume this? I know I can create a module like this:

define(['module'], function (module) {
    // insert and return library code here.
});

But that doesn't seem great. It seems like I would have to refactor some of their code to get that working (e.g., turn it all into an object and return that object). I see a lot of libraries using a different pattern where they use an immediately invoked function that defines the module on the window object and returns it.

(function() {

    var phoneformat = {};

    window.phoneformat = phoneformat;

    if (typeof window.define === "function" && window.define.amd) {
        window.define("phoneformat", [], function() {
            return window.phoneformat;
       });
    }

})();

** UPDATE ** Is there any reason not to just do this?

define(['lib/phoneformatter'], function(phoneformatter) {

});

I get access to all of my methods but now it seems they are global because I did not wrap the library in a define...


Solution

  • This ended up working for me:

    define(['module'], function (module) {
        // insert and return library code here.
    });
    

    I am not entirely sure why 'module' was necessary. But it doesn't work without it. Also, I just returned an object and attached functions to it like so:

    return {
        countryForE164Number: countryForE164Number,
        nextFunction: nextFunction,
        // more functions as needed.
    }
    

    There is not much in the way of documentation for using 'module' but from what I can ascertain: Module is a special dependency that is processed by requireJS core. It gives you information about the module ID and location of the current module. So it is entirely possible that I messed up the paths in config.