ES6 Modules
ES6 Modules (also known as ESM) represent the modern, official way to handle modules in JavaScript.
They are built directly into the ECMAScript language specification, meaning they are natively supported by modern web browsers and modern Node.js environments.
The Syntax
ES6 modules drop the clunky module.exports and require() syntax in favor of two clean keywords: export and import.
Exporting (math.js)
You place the export keyword directly in front of the variables or functions you wish to expose.
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
Importing (main.js)
You use the import keyword along with object destructuring to pull specific items from a file path.
import { add, subtract } from "./math.js";
console.log(add(1, 2)); // 3
Note: ES6 Modules use static analysis, meaning all import statements must be placed at the very top level of your file. They cannot be conditionally imported inside if statements or functions.