Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are extra advantage of using ES6 module instead of revealing module pattern?

I am exploring ES6 module and trying to figure out what extra advantage we get using ES6 module instead of closure along with module pattern(MP).

For example util.js in ES6.

   var util ={
         abc:function(){
        //function body
    },
    def:function(){
         // function body
    }
    export default utils;   // here export is exposing the entire object
}

util.js using closure & module pattern

var util = (function(){
       function _abc(){
         console.log("abc")
           // function body
       };
    function _def(){
         // function body
      }

  return{          // each of the function will be exposed
      abc:_abc,
      def:_def

}
}(util ||{}))

someFile.js in ES6

import {utils} from "path/to/file"

In someFile.js with closure & module pattern

util.abc() // Will log "abc"

Also I know es6 module allow us to rename imports & exports Like export { a as abc} .

With closure & module pattern we can give a name whatever we like inside return statement like return { a:_abc}

My question:What extra benefit we can get by using es6 module instead of closure& MP.One i guess is reduction in lines of code.

Please excuse me if I have missed any basic difference

like image 907
brk Avatar asked Mar 04 '16 10:03

brk


1 Answers

With var util = (function(){ bla bla bla }(util || {})); the global namespace is polluted, so that once you have used import {utils} from "path/to/file", it will remain in global namespace, i.e. you'll be have window.util everywhere, even after the module has finished it's work and replace by some other module. Now consider you have 100s of modules and you do it in the same way, then imagine how dirty would the poor window become!

However if ES6 Module or CommonJS or even AMD is used, then

  1. The global namespace is not polluted.
  2. [ES6] You can use export default something to export a default value to use import from "path/to/file"
  3. [ES6] You can export multiple things from ES6 Module, using export["anotherthing"]

Furthermore I would recommend you to read this blog post.

like image 186
Ammar Hasan Avatar answered Nov 11 '22 09:11

Ammar Hasan