ES2015 Export Internal Function

I am studying ES2015 export function. I tried to figure it out online, but my doubts are still unresolved.

When I declare an export inside an anonymous function, jshint shows the following error (at least inside the Intellij plugin):

E053 Export declaration must be in global scope.

In contrast, JSHint always requests the full code inside the Anonymous function. If I write the code as follows:

export const MY_CONSTANT = 1000; (function(){ 'use strict'; //Complete code goes here }(); 

We have to write a lot of code at the top and bottom of the page. Some code will go from the file to the beginning (or end) of the page.

+5
source share
2 answers

The best way I can explain this is with iJAcriptIIFE, a way to create encapsulation. You would put the code of your module inside one and back and an object of some type. If you needed to import the code, you would do it with an argument. The new module syntax allows you to do the same thing differently. Think of import as arguments for IIFE and export as return. Here is a complete explanation of export export syntax from Mozilla https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Further, if you want to learn more, I created some template that uses babel, gulp, browser and jasmine, so I can write all my code in es2015 format. https://github.com/jamesrhaley/es2015-babel-gulp-jasmine.git

+1
source

If you use the ES2015 module syntax, you probably do not need to wrap your code with an anonymous function, as the module loader processes the code that is exported.

I'm not sure about every module loader, but when using TypeScript + a browser, every file is wrapped to prevent the global namespace variables from overflowing. See Why import top-level import declarations are required in es2015 for more information on how to work with module syntax and why variables can be declared globally.

0
source

Source: https://habr.com/ru/post/1239722/


All Articles