ESM (ECMAScript Modules) are self-contained files that can be imported and exported. They make sharing code between modules easy and create reusable components. To enable ESM support, we can add the following line to the package.json
file:
{"type": "module"}
Once ESM support is enabled, ESM modules can be used in Node.js for different functionalities.
ESM named imports and exports are a feature of ESM (ECMAScript Modules) that are used to export and import specific variables and functions from a module in Node.js. For a named export, the export
keyword is used, followed by the name of the variable or function that needs to be exported. For a named import, the import
keyword is used followed by the name of the variable or function that needs to be imported, surrounded by curly braces.
Once ESM support is enabled, named imports and exports can be used in the program. Here are some examples of different applications of ESM named imports and exports:
To export a named variable, we use the export
keyword followed by the name of the variable we want to export. For example:
import { myVariable } from "./module.js"; console.log(myVariable);
In module.js
, it exports and sets the myVariable
variable.
In export-variable.js
:
Line 1: It imports myVariable
from module.js
.
Line 3: It prints myVariable
on the console.
To export a named function, we use the export
keyword followed by the name of the function we want to export. For example:
import { myFunction } from "./module.js"; console.log(myFunction());
In module.js
, it exports and defines the myFunction()
function.
In export-function.js
:
Line 1: It imports myFunction
from module.js
.
Line 3: It prints myFunction
on console.
To export a named class, we use the export
keyword followed by the name of the class we want to export. For example:
import { MyClass } from "./module.js"; const myClassInstance = new MyClass(); console.log(myClassInstance.myMethod());
In module.js
:
Line 1: It exports and defines the myClass
class.
Lines 2–4: The constructor prints the statement “MyClass instance created.”
Lines 6–7: The function myMethod()
returns the statement “Hello from myClass!”
In export-class.js
:
Line 1: It imports myClass
from module.js
.
Line 3: It initializes a class object myClassInstance
using the new
keyword.
Line 4: It prints myClassInstance.myMethod()
on console.
The named imports can be given different names when we import them by using the as
keyword. For example:
import { myVariable as myNewVariable, myFunction as myNewFunction} from "./module.js"; console.log(myNewVariable); console.log(myNewFunction());
In module.js
:
Line 1: It exports and sets the myVariable
variable.
Lines 2–3: It exports and defines the myFunction()
function.
In export-class.js
:
Line 1: It imports myVariable
as myNewVariable
and myFunction
as myNewFunction
from module.js
.
Line 3: It prints myNewVariable()
on console.
Line 4: It prints myNewFunction()
on console.
ESM modules have many advantages over the
Free Resources