Search code examples
javascriptecmascript-6es6-module-loader

What is the Point of "Import" in ES 6?


In other words, what is the difference between:

<!--index.html--> 
<script src="./fooFolder/lib.js"></script>

and

/*--app.js --*/
import * as lib from 'fooFolder/lib';

The file being accessed:

//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
    return x * x;
}
export function diag(x, y) {
    return sqrt(square(x) + square(y));
}

Is the main benefit of using the import statement that not everything is loaded immediately? But it seems that I still have to include the file references in the index, so that doesn't seem to be the case.

So, in short, what's the point (I am sure there is one, and I am completely missing it).


Solution

    1. Scoping and namespaces https://en.wikipedia.org/wiki/Scope_(computer_science)

    2. Code seperation and Testing, imports allow errors to be localised, less complex to test due to limited scope

    3. Compression and optimization, tools can figure out what code is or is not needed so you can focus on programming instead of dependency hunting

    4. Shared libraries, common packages use less boilerplate code

    Imports are a big part of good code architecture, I recommend you read something like Angular 2 architecture if you want to learn more https://angular.io/docs/ts/latest/guide/architecture.html