I am trying to learn to export and import modules in ES6 and it tells me in the console: SyntaxError: export declarations may only appear at top level of a module
I'm trying something simple. I have the code like this:
file.js
export default const modulo = function(){
alert("Hola mundo");
};
Could I then in an html page within a script tag do the following to test? page.html
import modulo from 'archivo.js';
According to MDN it should work but only the export already gives an error.
Why so much complication? Couldn't you use the revealing pattern instead? What advantages would ES6 modules offer over methods like Revealing with immediately executable functions that return an object (IIFE)? The use of these imports/exports prevents you from having to import the .js with the ?
You can do it perfectly, in fact, nothing prohibits you. JavaScript is so flexible that there are many ways to do the same thing. The RMP has the same goal as CommonJS, RequireJS, UMD and ES6 modules; using one or the other is a matter of personal judgment.
RMP is a fairly well designed and structured pattern, it allows you to write modules with private variables/functions in a practical and simple way. The truth is that it has both advantages and disadvantages.
Advantage
Disadvantages
It is well known that RMP has a weak point regarding the overriding of private properties since setters are needed, since an object literal does not work as a prototype. If you don't use getters, you'll need to use
this
since you'd need to put the variables directly into the object literal, and this of course breaks the ideology of this pattern.Actually there are no advantages worth highlighting, except for:
ES6 modules has nothing to do with importing an HTML script. Nothing has changed in this regard at all.
Extra
To date, no browser supports ES6 modules except for Safari Preview, but this is not a problem since with Babel we can port not only ES6 code, but also ES7/8 and ECMA proposals from even Stage 2. Traspile you just need to install the package
babel-cli
globally and the presets you want. For example:And you backpile any module to ES5:
Which generates you ES5 code compatible with any old and modern browser today.
ES6 is not yet 100% supported by browsers, here you can see a compatibility table.
The idea of this format is to encapsulate the classes and thus separate them into different files. It's made for people like me who come from object-oriented languages (Thank you very much!!! :)). For example, your function would be written like this:
and to import it as we already know
Now we can have several classes in our file
and when we import it we do it this way
The compiler then translates this into what all browsers know. when I say compiler I mean the babel so you have to "babelize" your code, it generally compiles everything into one. For example I use these dependencies to work on a react project and I have some scripts to compile and test it.