Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 module vs revealing module pattern

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?

like image 494
Jyoti Prasad Pal Avatar asked Sep 02 '17 07:09

Jyoti Prasad Pal


People also ask

What is the difference between a module and a revealing module?

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.

What is the module pattern in ES6?

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.

What's new in JavaScript ES6?

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.

What is the revealing module pattern in JavaScript?

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.


1 Answers

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:

  • ES6 modules have syntax for imports and exports
  • ES6 modules have named exports and a default export for if you just want to expose one class (or whatever).
  • ES6 module imports are statically analysed at parse time. If you try to import a non-existent property, you'll get an error.
  • ES6 module imports are "views" of the original variable, not assignments. (This may not be supported by some transpilers.)

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.

like image 160
Sean McMillan Avatar answered Oct 05 '22 08:10

Sean McMillan