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
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
export default something
to export a default value to use import from "path/to/file"
export["anotherthing"]
Furthermore I would recommend you to read this blog post.
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