How are namespace objects used with AMD in javascript?

In an attempt to make my libraries more portable, I read on AMD and CommonJS. The only thing I noticed above all is how they use the directory structure and strive to have one module for each file. From what I can say, their "namespaces" match the directory tree.

However, my own code uses the global object as a namespace, and then among my various files, regardless of directories, I add classes to this object.

(function (Twifty) {
    // Add objects to the Twifty namespace
    return Twifty;
}(Twifty || {}));

During the upgrade process, I try to support AMD and CommonJs. There are many articles on how to do this, but I cannot wrap my head around the define function . This is how I convert the above code:

(function (root, factory) {

    // Define the namespace if it doesn't exist
    var Twifty = root.Twifty || {};

    'use strict';
    if (typeof define === 'function' && define.amd) {
        // AMD is used - Register as an anonymous module.
        define([], factory);
    } else if (typeof exports === 'object') {
        // CommonJS is used - Twifty is a namespace and doesn't need to be required
        factory(Twifty);
    } else {
        // Neither AMD nor CommonJS used. Use global variables.
        if (!document) {
            throw 'twifty-map requires a DOM object';
        }
        root.Twifty = factory(Twifty);
    }

}(this, function(Twifty) {
    // Add objects to the Twifty namespace
    return Twifty;
}));

AMD define. factory Twifty, , . ?

, , .

, .

+4
1

AMD CommonJS .

, , ( ), .

twifty.base :

(function (root) {
    'use strict';

    if (typeof define === 'function' && define.amd) {
        // AMD 
        define([], {});
    }
    else if (typeof module === "object" && module.exports) {
        // CommonJS
        module.exports = {};
    } 
    else {
        root.Twifty = root.Twifty || {};
    }
}(this));

twifty.base:

(function (root, factory) {

    'use strict';
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['twifty.base'], factory);
    }
    else if (typeof module === "object" && module.exports) {
        // CommonJS
        module.exports = factory(require('twifty.base'));
    } 
    else {
        root.Twifty = factory(root.Twifty || {});
    }

}(this, function(Twifty) {
    Twifty.foo = 1;

    Twifty.bar = function () {};

    return Twifty;
}));

, , script , twifty.base . ( factory(root.Twifty || {}).) AMD CommonJS, twifty.base, AMD CommonJS , JavaScript.

+2

Source: https://habr.com/ru/post/1653041/


All Articles