Node.js Modules
Because Node.js predates the official ES6 Module specification, it uses the older CommonJS syntax by default.
If you try to use import and export in a standard Node.js file, it will crash. However, updating your Node.js project to support modern ES6 modules is incredibly simple.
Two Ways to Enable ES6 in Node
Option 1: The package.json method (Recommended)
The cleanest way to switch an entire project to use ES6 modules is to add a single configuration line to your package.json file:
{
"name": "my-project",
"type": "module"
}
By adding "type": "module", Node.js will automatically treat all .js files in your project as modern ES6 modules.
Option 2: The .mjs extension
If you have a massive legacy project and only want to write a few specific files using modern modules, you can change the file extension of those specific files from .js to .mjs (Module JavaScript). Node.js will strictly interpret .mjs files as ES6 modules.
A Note on Strict Mode
Remember, once you tell Node.js that your files are ES6 modules, Node automatically enforces Strict Mode across your entire codebase.