DEV Community

LG
LG

Posted on

1 1

CJS & ESM modules cross-compatibility

Two ways to be cross-compatible between Node's modules:

Scenario A.js : you're in ESM module & you want to require CJS :

// A.js
import { createRequire } from 'module'
const requireInESM = createRequire(import.meta.url)
requireInESM(path) // require CJS in this current module of ESM
Enter fullscreen mode Exit fullscreen mode

whilst,..

Scenario B.js : you're in CJS module & you want to import ESM:

// B.js
import (path); // use dynamic import to require ESM within current CJS module
Enter fullscreen mode Exit fullscreen mode

Found a typo, or want to improve something, leave a comment in the comment sections below . Thanks !

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More