How to create Javascript modules? – a basic example

Gone were the days when Javascript was a small kid on the block.

We used it only for client side validation and petty stuff.

Now it has grown bigger than many major languages and occupied the territory of server side programming as well.

Javascript for a long time didn’t support modules.

If you wanted to reuse code from a different javascript file , you wouldn’t have been able to!

During the year 2015 , ES6 , the javascript standard committee introduced modules.

And since then importing code from another javascript file became possible.

Here is a very basic example of how to create a javascript module and how to use it.

Let’s create a shopping application .

A shop makes orders to a factory to manufacture items.

And once manufactured it orders a courier service to pick them and ship them to its customers.

Here is how we could separate the logic and write there different javascript files for each task:

A factory file with a method to manufacture items:

factory.js:

 function manufacture(item){

    console.log("manufacturing item "+item);
}

A courier file with a method to ship items:

courier.js:

 function shipitem(item){

    console.log("Shipping "+item);
}

And a shop file to make use of the above two functions:

shop.js:

function order(){

console.log("Ordering");
    manufacture("pencil");
    shipitem("pencil");
}

Let’s say all these three files are in the same folder.

Will the above code work?

Will the method order() in the file shop.js be able to invoke the methods manufacture() and shipitem() in factory.js and courier.js files respectively?

No!

To make this work we need to make use of javascript modules.

First you need to export the methods from factory.js and courier.js.

So the refactored code will be like this:

factory.js:

 export function manufacture(item){

    console.log("manufacturing item "+item);
}

courier.js:

export function shipitem(item){

    console.log("Shipping "+item);
}

Notice the word export prefixed before each method.

This implies that the given method is exported to be available in other javascript files.

To import the exported files you need to import them using import statement in shop.js file.

Here is the updated shop.js file:

import {manufacture} from '/factory.js';
import {shipitem} from '/courier.js';
export function order(){

console.log("Ordering");
    manufacture("pencil");
    shipitem("pencil");
}

Notice the import methods .

The methods to be imported are placed between parenthesis separated by commas.

In our case we are importing just a single method from each file.

The relative path of the imported file should be specified after from keyword in the import statment.

Once imported you can call them.

Our javascript files are ready.

Now you can import shop.js file in your html.

There is a difference in the way you import though.

You need to import it as a module .

Here is how you do it:

shop.html file:


<head>
    <script type="module" >
        import {order} from '/shop.js';
        window.order = order;
    </script>
</head>




<html>

    <body>
        Hello!

        <button onclick="order()">Click me</button>
    </body>
</html>

This is a simple html file which calls the method order() in shop.js.

To invoke this you need to do the following:

  1. Import the script as a module:
<script type="module" >
        import {order} from '/shop.js';

    </script>

Use type=”module” statement in the script tag and then import the function using import statement as shown above.

2. Assign the function to window object

Any method in a javascript module is available only within the scope of the module. So to increase its scope outside of the module you can assign it to window object.

(You can also add an action listener to the button click inside the module code – not covering this here to keep this example simple)

Now the function order() is ready to be used.

3. Deploy on a http server

Usually if you want to invoke a javascript from a html file you can just simply load the html page in your browser and the javascript will get invoked.

But modules don’t work that way!

For security reasons mandated by browsers , you need to deploy them in a http/web server.

Here is the error what I got on trying to load the shop.html file directly on browser and click the button:

To make this work I deployed my html and javascript files to Apache Http server by following the steps highlighted here.

Once deployed, I clicked the button in shop.html file and it worked as expected:

That’s it!

This is a very basic example of how javascript modules work.

Here is the repository with the above code:

https://github.com/vijaysrj/javascriptmodules

For detailed features check here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules


Posted

in

,

by

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading