6

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?

Jyoti Prasad Pal
  • 1,569
  • 3
  • 26
  • 41
  • Possible duplicate of [What is the difference between browserify/requirejs modules and ES6 modules](https://stackoverflow.com/questions/28674652/what-is-the-difference-between-browserify-requirejs-modules-and-es6-modules) – try-catch-finally Sep 02 '17 at 07:32
  • IIFEs are poor man's modules. They don't handle dependencies and pollute global namespace for interoperation. You can pick any decent reading on ES modules and estimate how much of it is applicable to IIFEs. – Estus Flask Sep 02 '17 at 09:19

1 Answers1

3

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.

Sean McMillan
  • 10,058
  • 6
  • 55
  • 65
  • "as of 9/2017, node does not support ES6 modules". Hmmm. What is the recommended approach these days? I'm using Gulp (if that matters) and Babel. I'm trying to decide on an approach for structured / reusable code, but I'm a little lost. Is there an "agreed upon" approach for using ES6/Modules/Babel these days? The web app I'm working on is pretty large, so I need a decent code structure. – dmathisen May 13 '18 at 03:41
  • For your app's internal modules, use something that transforms and bundles, like rollup or webpack. I don't know what the best choice is if you're publishing modules to npm. `@std/esm` seems promising, but I haven't used it myself. – Sean McMillan May 16 '18 at 14:45