CHEAT SHEET
developers redhat.com | @RHOevelopers
ECMAScript Modules Cheat Sheet
This cheat sheet intraduces ECMAScript modules (ESM), an alternative to CommonJs modules for sharing functions in JavaScript programs. ESM are
the future of modules in JavaScript. ESM are already the standard format for front-end development, and now can be used on the back end with
recent versions of Nodejs. Although the old module system (Common)s) has worked for many years, ESM come with many benefits such as,
asynchronous loading, top-level awalt, and improved static analysis
‘The following cade exports the madule in the funTimes.mjs fle:
function funTimes0 {
return Fun’
>
export (funtimes
Mi
en oie)
‘The following cade Imports and runs the funTimes function fram the
funTimes.mjs ie:
Import (funTimes } from funtimes.ms
funTimest
Evens
Because Node js treats code as Common|$ modules by defaul
module authors will need to tell Nodes to treat the code as.
ECMAScript Modules by either using the smjs fle extension (as shown
In earlier examples) or by using the type fied in the package json fle:
11 package_son
‘
name; funTimes
type: “*module”
>
‘A default export allows a module to provide a default function:
i tunTimes.js
function funtimesd ¢
return ‘Fun
)
export default funTimes;
Importing this default function could leok something like this:
Happanis
import funTimes from ‘/funTimes.mis!
funtimest):