Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES2015 Export inside function

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.

like image 483
Rohit Manglik Avatar asked Jan 03 '16 13:01

Rohit Manglik


1 Answers

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

like image 108
jamesRH Avatar answered Sep 25 '22 19:09

jamesRH