Getting Back to Where We All Started
Years ago, when I was developing Java J2EE applications, I was jealous of the front-end developers that could just save a HTML file and refresh the browser to see their changes. With J2EE, we wrote JSP files that had to be compiled, then a server had to be started to serve our content up. The simpler development cycle was one reason I started to enjoy doing front-end development.
So front-end development used to be easy, then it got harder — let’s work towards making it easier again.
ES Modules to the Rescue
Here is an example application with the structure we are using for web components. I’m showing a list of people and if you click on the person it will show you the details of this person.
Our build files has just one line, build.js. require(‘../dist/people-list’); The WebPack will use this file as the entry file and build data.js as its output. The info, list, and data files are our web components.
We can now serve this page up and see a list of characters. Structuring our code this way will allow us to move to ES modules quickly. ES modules are starting to land in browsers. They’re currently in:
- Safari 10.1
- Chrome Canary 60 — Behind the Experimental Web Platform flag in chrome:flags Firefox 54 — Behind the dom.moduleScripts.enabled setting in about:config
To change our code to use ES modules all we have to do us update our index.html. To use modules all we need to do is add type+module this script as a ECMAScript module.This will tell the browser to treat this script as a ECMAScript module.
So our index.html turns into this:
needed. We can also use the attribute nomodule on the script tag to add a fallback if the browser does not
support ES modules.
Our final index.html looks like this:
We now can take advantage of modular code without using WebPack. There are some other advantages as well such as by leveraging imports to only use the parts of the code we want to use. We can also go back to using individual files which makes development and debugging a lot easier to work with. With individual files we can also take advantage of HTTP2 and load the code in one pipe with faster download.
ES modules allow us to write our code in modules, create local scope, and avoid polluting the global scope with our functions. We can shrink the size of our code using tree shaking from bundle applications like WebPack. We can also enjoy easier unit testing of our module code.
In the near future, we will be able to use ES modules native in the browser. This will allow us additional benefits such as http2 support, modules executing only once, async loading, and many more!
DISCLOSURE STATEMENT: These opinions are those of the author. Unless noted otherwise in this post, Capital One is not affiliated with, nor is it endorsed by, any of the companies mentioned. All trademarks and other intellectual property used or displayed are the ownership of their respective owners. This article is © 2017 Capital One.