DEV Community

LG
LG

Posted on

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)