Welcome!

Blog Feed Post

ECMAScript 6 modules in the browser with Traceur

ECMAScript 6 standardizes the syntax of modules. A module is simply a Javascript file that you can load either on the application startup or lazily on the as-needed basis. ES6 modules give you complete control on what code to export to the external scripts and what to keep private to the module. Prepend a variable, a function, or a class definition with the keyword export, and all other scripts in your project can import the module’s API using the import keyword. For details of using modules, read this great post by Dr. Alex Rauschmayer.

But the ECMAScript 6 specification doesn’t define module loaders, which can be used both in the browsers and in the standalone JavaScript engines. Eventually all Web browsers will support the System object that knows how to import modules, but meanwhile you can use the polyfill ES6 Module Loader or, if you want to go fancy and ensure that your AMD and/or CommonJS modules are also loaded in a standardized fashion, go with the universal system module loader called SystemJS.

Since ES6 syntax is not fully supported by any of the modern browsers, you’d need to transpile the code from ES6 to ES5 using one of the transpilers such as Traceur or Babel. In this blog I’ll show you how to dynamically load ES6 modules in the Web browsers with auto-transpiling using Traceur. To run this example on your computer you’ll need to have node.js with npm installed.

First, you need to download and install es6-module loader in any directory by running the following npm command:

npm install es6-module-loader

Then create an application folder and copy the file es6-module-loader.js there (this is a minimized version of the loader that was downloaded by npm). Our sample application will have two additional files: moduleLoader.html and shipping.js. For simplicity I’ll keep all these files in the same folder.

Imagine that we develop an online store with a large code base. To avoid creating a monolithic application, we’ve split it into loadable modules. In particular, the module that handles shipping should be loaded only if the user clicks the Shipping button. Here’s the code of our “huge” shipping module:

export function ship() {
    console.log("Shipping products...");
}

function calculateShippingCost(){
    console.log("Calculating shipping cost");
}

Since I used the export keyword only in front of the ship() function, the function calculateShipptingCost() will remain private for the module and won’t be accessible from the outside. No need to implement the module design pattern with immediately-invoked function expressions, and no need to use a third-party framework like RequireJS.

The file moduleLoader.html includes a script that loads and uses the shipping module. In this example I use Traceur for the on-the-fly transpiling of the ES6 code to ES5 so it can run in any browser. Here’s the file moduleLoader.html:

<!DOCTYPE html>
<html>
<head>
    <title>modules.html</title>
    <script src="https://google.github.io/traceur-compiler/bin/traceur.js"></script>
    <script src="es6-module-loader.js"></script>
</head>
<body>

  <button id="shippingBtn">Load the Shipping Module</button>

<script>

let btn = document.querySelector('#shippingBtn');
btn.addEventListener('click', () =>{

     System.import('shipping')
         .then(function(module) {
             console.log("Shipping module Loaded ", module);

             module.ship();

             module.calculateShippingCost();  // will throw an error
         })
         .catch(function(err){
             console.log("In error handler", err);
         });
});

</script>

</body>
</html>

in Line 5 we load the Traceur for transpiling. In line 6 we load es6-module-loader to support the System object that will load the shipping module using the import() call when the user clicks on the button. The import returns the ES6 Promise object, and when the module is loaded, the function specified in then() will be executed. In case of an error the control goes to the function catch().

Inside the then() we print the message on the console and invoke the exported function ship(). After that we try to invoke the module’s function calculateShippingCost(), which will result in error because this function was not exported and remain private.

NOTE: When you have the inline script in the HTML file, you should use type="module" to make sure that the Traceur transpile it to ES5. Without it, the browser that don’t support the let keyword (line 14) and arrow functions (line 15) would complain.

To see this code in action you need to serve it using some Web server. I use WebStorm IDE for development, which comes with embedded Web server. Lets run moduleLoader.html in Google Chrome and open Chrome Developer Tools. This is my Chrome browser looks after I clicked on the button Load the Shipping Module:

7

Look at the XHR tab in the middle of the window. The HTML page has loaded shipping.js after I clicked on the button. The size of this file is 91 bytes, which is really small and making an additional network call to get it seems like an overkill. But if the application consists of 10 modules 500KB each, modularization with lazy loading makes sense.

At the bottom, on the console tab you see the message from the script in moduleLoader that the shipping module was loaded. Then it calls the function from ship() from the shipping module, and generates an error trying to call the function calculateShippingCost() as expected.

In the real-world projects you should integrate transpiling in the project build, but I just wanted to illustrate the ease of the transpiling in the Web browser without any additional preparations. Transpilers allow you to start programming in ECMAScript today. If you live in the New York Area, I invite you to enroll into my one day Intro to JavaScript workshop.


Read the original blog entry...

More Stories By Yakov Fain

Yakov Fain is a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs (http://yakovfain.com) and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @yfain

Latest Stories
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
The session is centered around the tracing of systems on cloud using technologies like ebpf. The goal is to talk about what this technology is all about and what purpose it serves. In his session at 21st Cloud Expo, Shashank Jain, Development Architect at SAP, will touch upon concepts of observability in the cloud and also some of the challenges we have. Generally most cloud-based monitoring tools capture details at a very granular level. To troubleshoot problems this might not be good enough.
As popularity of the smart home is growing and continues to go mainstream, technological factors play a greater role. The IoT protocol houses the interoperability battery consumption, security, and configuration of a smart home device, and it can be difficult for companies to choose the right kind for their product. For both DIY and professionally installed smart homes, developers need to consider each of these elements for their product to be successful in the market and current smart homes.
Infoblox delivers Actionable Network Intelligence to enterprise, government, and service provider customers around the world. They are the industry leader in DNS, DHCP, and IP address management, the category known as DDI. We empower thousands of organizations to control and secure their networks from the core-enabling them to increase efficiency and visibility, improve customer service, and meet compliance requirements.
In his session at 21st Cloud Expo, Michael Burley, a Senior Business Development Executive in IT Services at NetApp, will describe how NetApp designed a three-year program of work to migrate 25PB of a major telco's enterprise data to a new STaaS platform, and then secured a long-term contract to manage and operate the platform. This significant program blended the best of NetApp’s solutions and services capabilities to enable this telco’s successful adoption of private cloud storage and launchi...
DevOps is often described as a combination of technology and culture. Without both, DevOps isn't complete. However, applying the culture to outdated technology is a recipe for disaster; as response times grow and connections between teams are delayed by technology, the culture will die. A Nutanix Enterprise Cloud has many benefits that provide the needed base for a true DevOps paradigm. In their Day 3 Keynote at 20th Cloud Expo, Chris Brown, a Solutions Marketing Manager at Nutanix, and Mark Lav...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
Cloud Expo, Inc. has announced today that Andi Mann and Aruna Ravichandran have been named Co-Chairs of @DevOpsSummit at Cloud Expo Silicon Valley which will take place Oct. 31-Nov. 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. "DevOps is at the intersection of technology and business-optimizing tools, organizations and processes to bring measurable improvements in productivity and profitability," said Aruna Ravichandran, vice president, DevOps product and solutions marketing...
Digital transformation is changing the face of business. The IDC predicts that enterprises will commit to a massive new scale of digital transformation, to stake out leadership positions in the "digital transformation economy." Accordingly, attendees at the upcoming Cloud Expo | @ThingsExpo at the Santa Clara Convention Center in Santa Clara, CA, Oct 31-Nov 2, will find fresh new content in a new track called Enterprise Cloud & Digital Transformation.
Most technology leaders, contemporary and from the hardware era, are reshaping their businesses to do software. They hope to capture value from emerging technologies such as IoT, SDN, and AI. Ultimately, irrespective of the vertical, it is about deriving value from independent software applications participating in an ecosystem as one comprehensive solution. In his session at @ThingsExpo, Kausik Sridhar, founder and CTO of Pulzze Systems, will discuss how given the magnitude of today's applicati...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
SYS-CON Events announced today that mruby Forum will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. mruby is the lightweight implementation of the Ruby language. We introduce mruby and the mruby IoT framework that enhances development productivity. For more information, visit http://forum.mruby.org/.
The dynamic nature of the cloud means that change is a constant when it comes to modern cloud-based infrastructure. Delivering modern applications to end users, therefore, is a constantly shifting challenge. Delivery automation helps IT Ops teams ensure that apps are providing an optimal end user experience over hybrid-cloud and multi-cloud environments, no matter what the current state of the infrastructure is. To employ a delivery automation strategy that reflects your business rules, making r...
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp emp...
In his general session at 21st Cloud Expo, Greg Dumas, Calligo’s Vice President and G.M. of US operations, will go over the new Global Data Protection Regulation and how Calligo can help business stay compliant in digitally globalized world. Greg Dumas is Calligo's Vice President and G.M. of US operations. Calligo is an established service provider that provides an innovative platform for trusted cloud solutions. Calligo’s customers are typically most concerned about GDPR compliance, applicatio...