Modules in JavaScript
Today, in Node.js, there are two ways to create and use JavaScript modules. One is historical, non-standard, and the other is standard (ESM for ECMAScript Module) and has been implemented in Node since version 12 experimentally, and since Node 16 the API is stable.
We will only look at the standard way.
In JavaScript, each file is a module if we use the ESM syntax.
Syntax
It is the import
/ export
syntax:
js
import process from 'node:process'
console.log(process.env.PATH)
process
is a native Node module that we import into the index.js
module with the import
keyword.
Default Export
In the previous example, process
is the default export: there are no curly braces around it.
Here is another example of a default export:
js
import add from './utils.js'
console.log(add(1, 2))
js
export default function add(a, b) { // `default` keyword
return a + b
}
Named Export
Here, add
is a named export: curly braces are required around it (note the absence of the default
keyword in utils.js
)
js
import { add } from './utils.js'
console.log(add(1, 2))
js
export function add(a, b) { // No `default` keyword
return a + b
}