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)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay