Welcome!

Machine Learning Authors: Elizabeth White, William Schmarzo, Jnan Dash, Pat Romanski, Liz McMillan

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

@CloudExpo Stories
Enterprises are adopting Kubernetes to accelerate the development and the delivery of cloud-native applications. However, sharing a Kubernetes cluster between members of the same team can be challenging. And, sharing clusters across multiple teams is even harder. Kubernetes offers several constructs to help implement segmentation and isolation. However, these primitives can be complex to understand and apply. As a result, it’s becoming common for enterprises to end up with several clusters. Thi...
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
"ZeroStack is a startup in Silicon Valley. We're solving a very interesting problem around bringing public cloud convenience with private cloud control for enterprises and mid-size companies," explained Kamesh Pemmaraju, VP of Product Management at ZeroStack, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Codigm is based on the cloud and we are here to explore marketing opportunities in America. Our mission is to make an ecosystem of the SW environment that anyone can understand, learn, teach, and develop the SW on the cloud," explained Sung Tae Ryu, CEO of Codigm, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Infoblox does DNS, DHCP and IP address management for not only enterprise networks but cloud networks as well. Customers are looking for a single platform that can extend not only in their private enterprise environment but private cloud, public cloud, tracking all the IP space and everything that is going on in that environment," explained Steve Salo, Principal Systems Engineer at Infoblox, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventio...
The question before companies today is not whether to become intelligent, it’s a question of how and how fast. The key is to adopt and deploy an intelligent application strategy while simultaneously preparing to scale that intelligence. In her session at 21st Cloud Expo, Sangeeta Chakraborty, Chief Customer Officer at Ayasdi, provided a tactical framework to become a truly intelligent enterprise, including how to identify the right applications for AI, how to build a Center of Excellence to oper...
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
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...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, discussed how by using ne...
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Agile has finally jumped the technology shark, expanding outside the software world. Enterprises are now increasingly adopting Agile practices across their organizations in order to successfully navigate the disruptive waters that threaten to drown them. In our quest for establishing change as a core competency in our organizations, this business-centric notion of Agile is an essential component of Agile Digital Transformation. In the years since the publication of the Agile Manifesto, the conn...
In his session at 21st Cloud Expo, James Henry, Co-CEO/CTO of Calgary Scientific Inc., introduced you to the challenges, solutions and benefits of training AI systems to solve visual problems with an emphasis on improving AIs with continuous training in the field. He explored applications in several industries and discussed technologies that allow the deployment of advanced visualization solutions to the cloud.
Vulnerability management is vital for large companies that need to secure containers across thousands of hosts, but many struggle to understand how exposed they are when they discover a new high security vulnerability. In his session at 21st Cloud Expo, John Morello, CTO of Twistlock, addressed this pressing concern by introducing the concept of the “Vulnerability Risk Tree API,” which brings all the data together in a simple REST endpoint, allowing companies to easily grasp the severity of the ...
While some developers care passionately about how data centers and clouds are architected, for most, it is only the end result that matters. To the majority of companies, technology exists to solve a business problem, and only delivers value when it is solving that problem. 2017 brings the mainstream adoption of containers for production workloads. In his session at 21st Cloud Expo, Ben McCormack, VP of Operations at Evernote, discussed how data centers of the future will be managed, how the p...
"NetApp is known as a data management leader but we do a lot more than just data management on-prem with the data centers of our customers. We're also big in the hybrid cloud," explained Wes Talbert, Principal Architect at NetApp, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
"We're focused on how to get some of the attributes that you would expect from an Amazon, Azure, Google, and doing that on-prem. We believe today that you can actually get those types of things done with certain architectures available in the market today," explained Steve Conner, VP of Sales at Cloudistics, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.