Reputation: 377
I am learning export feature of ES2015. I tried understanding it online but my doubts are still not resolved
When I declare export inside a anonymous function, jshint shows following error (at least inside Intellij plugin):
E053 Export declaration must be in global scope.
On the contrary, JSHint always asks to wrap up whole code inside Anonymous function. If I write code in following way:
export const MY_CONSTANT = 1000;
(function(){
'use strict';
//Complete code goes here
}();
We have to write a lot of code in top and bottom of the page. Some code will jump from between the file to the beginning (or end) of page.
Upvotes: 6
Views: 2968
Reputation: 440
The best way I can explain it is the javascript IIFE was way of creating encapsulation. You would place the code of your module inside one and return and object of some kind. If you needed to import code into it you would do so with the argument. The new module syntax lets you do the same in a different fashion. Think of the the imports as arguments to the IIFE and the exports as the return. Here is the full explanation for import export syntax from Mozilla https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
Further more if you want to explore more I have created some boilerplate that uses babel, gulp, browserify, and jasmine so I can write all of my code going forward as es2015. https://github.com/jamesrhaley/es2015-babel-gulp-jasmine.git
Upvotes: 2
Reputation: 10569
If you are using ES2015 module syntax you probably don't need to wrap your code in an anonymous function since the module loader handles what code is exported.
I'm not sure about every module loader but when using TypeScript + browserify, each file gets wrapped to prevent variables cluttering the global namespace. See Why must export import declarations be on top level in es2015 for more on how to work with the module syntax and why variables can be declared globally.
Upvotes: 0