ECMAScript Module (Esm)

Definition

  • Works with ES2015 (ES6)
  • ESM6 syntax are often used in browser with import and export statement
  • For ES6 syntax to be used in Node.js, we have a few options:
    1. Name the file name .mjs if we want to use import / export in that file
    2. Define the "type": "module" in package.json to apply it for all .js file to support import/export syntax
    3. Use BalbelJS to transpile the file to use CommonJS (CJS) syntax
  • Import/export in ES6 is asynchronously
  • Has Tree-shakeable (remove unused dependency)
  • Might not support in older browser

Syntax

Export

// src/logger.js
class Logger {  
    log(content) {  
        console.log(content)  
    }  
}  
  
export default new Logger()

Import

// index.js
import Logger from './src/logger.js';  
var data = [1, 2, 2, 3, 4, 5, 5, 5, 6];  
Logger.log(data);

Execution

Node.js

In node-js we can specify the "type": "module" in package.json to enable import/export for all .js file

// package.json
{  
  "name": "server",  
  "version": "1.0.0",  
  "dependencies": {  
  },  
  "type": "module"  
}
node index.js

Browser

In browser we can specify type="module" in html to enable import/export

<!-- index.html -->

<html>  
    <body>Example requirejs</body>  
    <script type="module" src="index.js"></script>  
</html>