1.How are ES6 modules different from module pattern implemented using IIFE and closure? 2.Which one should be preferred over the other? Can some help with an example?
The revealing module pattern is really almost the same as the module pattern. The major difference to be aware of is simply how the revealing module pattern exposes it’s api. In other words, what is contained in the return statement of the revealing module pattern is different than what is in the module pattern.
The module pattern simply allows you to keep units of code cleanly separated and organized. Modules promote encapsulation, which means the variables and functions are kept private inside the module body and can't be overwritten. Creating a module in ES6 is quite simple. ES6 also allows us to export the module as default.
Something to note, the next version of JavaScript ES6 has a new specification for asynchronous module loading. You can use the module patterns that will be covered with the new ES6 module loading syntax.
To be fair, the revealing module pattern is very similar to the module pattern, but it has a really nice way of exposing the api of a module to it’s users or consumers. I think you’ll find the revealing module pattern to be a really good balance of how to structure your JavaScript code for readability.
The revealing module pattern is basically a cool trick invented to make something module-like in an ES5 environment. If you are in an environment where you can use ES6 modules, you should use those instead.
If you are not in an environment where you can use ES6 modules* You should use an ES6 transpiler (such as Babel) to compile modular source code into a format that can be used in your target environment.
A short list of the differences:
ECMAScript 6 modules: the final syntax is a really good summary of the way ES6 modules work.**
*as of 9/2017, node does not support ES6 modules. There is support in some browsers, but no major libraries take advantage of it yet.
**The Browser API it discusses, System.import is not how that part ended up working though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With