Search code examples
javascriptamdcommonjs

Allowing a Javascript module (class) to be used with CommonJS, AMD or neither


I have created a simple Javascript module. I'd like this to be available to CommonJS implementations, AMD implementations and global ()

Here is my class:

function Geolocation( callback ){
    this._latitude          = null;
    this._longitude         = null;
    this._accuracy          = null;
}

Geolocation.prototype = {
    //prototype definitions in here
}

Is what I am trying to achieve possible? An exhaustive google search has not yielded any results


Solution

  • (function (global, factory) {
        if (typeof define === "function" && define.amd) define(factory); //AMD
        else if (typeof module === "object") module.exports = factory(); //CommonJS
        else global.Geolocation = factory(); // for example browser (global will be window object)
    }(this, function () {
    
    var Geolocation = function( callback ){
        this._latitude          = null;
        this._longitude         = null;
        this._accuracy          = null;
    }
    
    Geolocation.prototype = {
        //prototype definitions in here
    }
    
    return Geolocation;
    
    }));