For example, this is a CommonJS module that exports two functions:
module.exports.add = function(a, b) {
return a + b;
}
module.exports.subtract = function(a, b) {
return a - b;
}
We can also import the public functions into another Node.js script using require(), just as we do here:
const {add, subtract} = require('./util')
console.log(add(5, 5)) // 10
console.log(subtract(10, 5)) // 5
참고 : https://blog.logrocket.com/commonjs-vs-es-modules-node-js
For example, here’s a simple ES module (with an .mjs extension) exporting two functions for public use:
// util.mjs
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
We can then import both functions using the import statement:
// app.mjs
import {add, subtract} from './util.mjs'
console.log(add(5, 5)) // 10
console.log(subtract(10, 5)) // 5
Another way to enable ES modules in your project can be done by adding a "type: module" field inside the nearest package.json file (the same folder as the package you’re making):
{
"name": "my-library",
"version": "1.0.0",
"type": "module",
// ...
}