Про модули в JavaScript

Всю информация о развития модулей описана в хорошей статье эволюция модульного JavaScript на хабре.

В repl rollup.js результат обработки исходного кода в разные модульные системы:

main.js - entrypoint

import { cube } from './maths.js';

console.log( cube( 5 ) ); // 125

maths.js

// This function isn't used anywhere, so
// Rollup excludes it from the bundle...
export function square ( x ) {
    return x * x;
}

// This function gets included
export function cube ( x ) {
    // rewrite this as `square( x ) * x`
    // and see what happens!
    return x * x * x;
}

ES

// maths.js

// This function gets included
function cube ( x ) {
    // rewrite this as `square( x ) * x`
    // and see what happens!
    return x * x * x;
}

/* TREE-SHAKING */

console.log( cube( 5 ) ); // 125

AMD

define(function () { 'use strict';

    // maths.js

    // This function gets included
    function cube ( x ) {
        // rewrite this as `square( x ) * x`
        // and see what happens!
        return x * x * x;
    }

    /* TREE-SHAKING */

    console.log( cube( 5 ) ); // 125

});

CJS

'use strict';

// maths.js

// This function gets included
function cube ( x ) {
    // rewrite this as `square( x ) * x`
    // and see what happens!
    return x * x * x;
}

/* TREE-SHAKING */

console.log( cube( 5 ) ); // 125

IIFE

(function () {
    'use strict';

    // maths.js

    // This function gets included
    function cube ( x ) {
        // rewrite this as `square( x ) * x`
        // and see what happens!
        return x * x * x;
    }

    /* TREE-SHAKING */

    console.log( cube( 5 ) ); // 125

}());

UMD

(function (factory) {
    typeof define === 'function' && define.amd ? define(factory) :
    factory();
}((function () { 'use strict';

    // maths.js

    // This function gets included
    function cube ( x ) {
        // rewrite this as `square( x ) * x`
        // and see what happens!
        return x * x * x;
    }

    /* TREE-SHAKING */

    console.log( cube( 5 ) ); // 125

})));

System

System.register('myBundle', [], function () {
    'use strict';
    return {
        execute: function () {

            // maths.js

            // This function gets included
            function cube ( x ) {
                // rewrite this as `square( x ) * x`
                // and see what happens!
                return x * x * x;
            }

            /* TREE-SHAKING */

            console.log( cube( 5 ) ); // 125

        }
    };
});

Похожие записи

JS. Get query param

function getQueryParam(item) {
  var svalue = window.location.search.match(new RegExp('[\?\&]' + item + '=([^\&]*)(\&?)', 'i'));
  return svalue ? svalue[1] : svalue;
}

// /foo/bar/baz.html?lang=ru
var lang = getQueryParam('lang') || 'en';