In the beginning, JS did not have a way to import/export modules. This was a problem for many developers and if you don’t believe then picture this. You’re writing an app in just a single file, I know I know it would be a nightmare.
So as time progress, people of higher intellect than myself attempted to add modularity to javascript. The ones that shouldn’t surprise you is UMD and ESM but there are others of course like CommonJS, Native JS and AMD. There are several others but the two from above are considered some of the big players
I am going to tackle some brief information like syntax, purpose and common behaviors. My goal is to help others that may be confused when dealing with particular issues with modules.
UMD
Universal Module Definition or as referenced UMD.
– Works on front and back end (hence the name universal).
– Unlike the other modules, UMD is more like a pattern to configure several module systems. Check out other patterns
– UMD is usually used as a fallback module when using bundler like rollup/Webpack
(function (root, factory) {
if (typeof define === "function" && define.amd) {
define(["jquery", "underscore"], factory);
} else if (typeof exports == "object") {
module.exports = factory(require("jquery"), require("underscore"));
} else {
root.Requester = factory(root.$, root._);}}(this, function ($,_) { //this is where I defined my module implementation var Requester = {//...};
return Requester;}));
ESM
ES Module short as ESM. It is javascript’s proposal to implement as standard module system. I am sure many of you have seen this: import React from 'react'
- Works in many modern browsers
- Tree-shakeable, due to ES6’s static module structure
- ESM allows bundlers like rollup to remove unnecessary code, allowing sites to ship less code to get faster load
- can be called in HTML
<script type="module"> import {func1} from 'my-lib';
func1(); </script>
Summary
– ESM is the best module format thanks to its simple syntax, async nature, and tree-shakeability.
– UMD works everywhere and usually used as a fallback in case ESM does not work
Thanks for reading, devs! In the future, I plan to write in depth about each module, especially ESM because it is packed with many awesomeness.