Showing posts with label RequireJS. Show all posts
Showing posts with label RequireJS. Show all posts

Wednesday, 26 September 2018

JavaScript modules, export and import

Let's consider web app project root directory which contains the following files:

scripts/common.js
scripts/array_demo.js
views/array_demo.html


Without modules:


scripts/common.js:

function clearElement(id) {...}
function log(text) {...}

scripts/array_demo.js:

function foo() {
    clearElement(...);
    log(...);
};

In HTML file scripts have to be added in order so functions, objects, or primitive values from previously included scripts are visible in scripts that use them:

views/array_demo.html:

         ...
         <script src='/scripts/common.js'></script>
         <script src='/scripts/array_demo.js'></script>
     </body>
 </html>

This can be a problem in case when there are many and/or complex dependencies. The solution is using ECMAScript modules. This will work in HTML5-compliant browsers.


With modules:


What is the difference between a common (classic) JavaScript script and a module?


A classic script is just a standard JavaScript script as you know it. A module script is one that contains an ES6 module, i.e. it uses (or: can use) import and export declarations. [source]

scripts/common.js:

function clearElement(id) {...}
function log(text) {...}

export {
    clearElement,
    log
};

scripts/array_demo.js:

import { clearElement, log} from './common.js';

function foo() {
    clearElement(...);
    log(...);
};

views/array_demo.html:

         ...
         <script type="module" src='/scripts/array_demo.js'></script>
     </body>
 </html>


export and import statements are defined in ECMAScript 2015 (6th Edition, ECMA-262).

module script type is available only in HTML5-compliant browsers [source].

Modules VS Require.JS


Require.JS "modularizes" JS scripts and basically emulates import/export functionality. With ES6 modules available there is no need to use Require.JS.

Further reading:


ECMAScript modules in browsers
ES6 In Depth: Modules
HTML/Element/script (MDN)
ECMAScript 6 modules: the final syntax
export (MDN)
import (MDN)
CommonJS vs AMD vs RequireJS vs ES6 Modules