0

I don't really understand what does the export keyword in ES6. Cause when I do something like the first exemple here, but without export anything in ES5 it's still works.

//------ lib.js ------

var sqrt = Math.sqrt;
function square(x) {
    return x * x;
}
function diag(x, y) {
    return sqrt(square(x) + square(y));
}

//------ main.js ------

console.log(square(11)); // 121
console.log(diag(4, 3)); // 5

So of course I know that I miss a big part, that's why I'm looking for some explanation or link that explain what I need to learn cause I don't find anything :)

8
  • when I do something like above - there's nothing above!! Commented Sep 11, 2015 at 14:19
  • 56 seconds later, google search resulted in exploringjs.com/es6/ch_modules.html Commented Sep 11, 2015 at 14:20
  • @JaromandaX Like the code in my post. I have updated my post considering your comment, hope it's more clear. Commented Sep 11, 2015 at 14:36
  • 1
    export (and import) are used in modules. If you are not using modules then you don't use them. Commented Sep 11, 2015 at 15:08
  • 1
    I deepened my research, I think I confused a module and a js file called in the script tag. For a module, it's the javascript file that call the module itself. So if I well understand, in this : import * as lib from 'lib'; lib is a path and never called in a script tag ? Commented Sep 11, 2015 at 15:34

1 Answer 1

1

The ES5 version will certainly work in the browser if you use regular script tags and put first lib.js and then main.js.

<head>
  <script src="./lib.js"></script>
  <script src="./main.js"></script>
</head>

Why does it work on the browser in ES5?

function square() and function diag() are global functions and can be accessed from anywhere :(

For example from Chrome dev console. enter image description here

What is different with the ES6 version?

The lib.js functions are not leaking out to the world and are going to be only available to whoever imports them.

For example:

import { square, diag } from './lib';

This imports the module and then decomposes it and it is only going to have access to square and diag, but not sqrt

As mentioned here you could also import the complete lib module. You can also import the complete module:

import * as lib from 'lib';
console.log(lib.square(11)); // 121
console.log(lib.diag(4, 3)); // 5
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you ! That answers my question completely, I confused two cases of different uses :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.