ES6 modules
ES6 is the first time JavaScript has built in modules.
The goal of ES6 modules was to create a format that both users of CommonJS and of AMD are happy with. Its syntax is even more compact than CommonJS. Their structure can be statically analyzed. Their support of cyclic dependencies is better than CommonJS. Similar to AMD, they have direct support for asynchronous loading and configurable module loading.
Use of native JavaScript modules is dependent on the import
and export
statements.
// file name "sum.js"
function sum(a, b) {
return a+b;
}
export { sum };
// file name "main.js"
import { sum } from "./sum.js";
let result = sum(1,2);
console.log(result); //3
<script type="module" src="main.js"></script>
To get modules to work correctly in a browser, you need to make sure that your server is serving them with a Content-Type
header that contains a JavaScript
MIME type such as text/javascript
References
Categories :
ES6
JavaScript