Apparently, ES6 doesn't need namespacing because each file is a
separate module.
This is misinformation. As far as I know, only files that use export
are ES6 modules. Without export
, an ES6 file is just an ordinary script that has access to the global scope unless it is either wrapped in an IIFE or is transformed during a build process.
Revision (12 July 2016): Apparently, I corrected misinformation with more misinformation. As Kyle Simpson clarifies below, "According to the current spec, what makes a file an ES6 module is how the environment (node, browser, etc) chooses to load it, not its contents."
In You Don't Know JS: ES & Beyond, Kyle Simpson, a.k.a. @getify, states
"Modules do still have access to window and all the "globals" that
hang off it, just not as lexical top-level scope. However, you really
should stay away from the globals in your modules if at all possible."
Now to your questions.
[I]sn't the second way, i.e., creating a custom namespace with an
IIFE, better than the first?
That depends on the environment in which your module is running. For example, in node
, there is no Window
object; therefore, in that environment there is no need to worry about your modules polluting the global namespace.
On the other hand, in the browser, Window
is a global web API, and your module does have access to it. Technically, anything your module attaches to Window
is not, strictly speaking, global; however, anything that is attached to Window
is so close to a global that it is generally considered to be a bad practice to modify it except through Window
's own API.
[H]ow do I avoid global namespace interference?
and
[I]s there a newer/nicer way of doing this in ES2015?
I don't know what the best practices are for dealing with scope in ES6. For the time being, I do the following:
- If a file is a module, it's top-level scope is the file itself, so I don't concern myself with global scope.
- If a file is not a module, I wrap it in an IIFE.
Source: You Don't Know JS: ES & Beyond
Also Recommended: ES6 In Depth: Modules by Jason Orendorff
alert()
anyway. – Diminutivewindow
has lots of properties. My app will have some too, and I want to avoid potential name collisions. Please see my updated question. – Ogawaalert === window.alert
? If so, that is not the case in a true ES6 environment, though it might with a transpiler. It definitely isn't the case when using ES6 modules with a proper module bundler. – Diminutivebody
tag, myindex.html
references a Babel compilation ofscripts/main.js
. Babel doesn't wrap my code in an IIFE for me. I updated my question. – Ogawa