Skip to content

Instantly share code, notes, and snippets.

@diauweb
Created September 21, 2021 01:48
Show Gist options
  • Save diauweb/f9f7be271ecc7bc0aecaf3dc891e18d2 to your computer and use it in GitHub Desktop.
Save diauweb/f9f7be271ecc7bc0aecaf3dc891e18d2 to your computer and use it in GitHub Desktop.
Requiring a ES Module into CJS environment
/**
* @file import compiled ES modules as a workaround
*/
const esm = require('esm')
const fs = require('fs')
const Module = require('module')
// Node: bypass [ERR_REQUIRE_ESM]
const orig = Module._extensions['.js']
Module._extensions['.js'] = function (module, filename) {
try {
return orig(module, filename)
} catch (e) {
if (e.code === 'ERR_REQUIRE_ESM') {
const content = fs.readFileSync(filename, 'utf8')
module._compile(content, filename)
}
}
}
const _esmRequire = esm(module, {
cjs: true,
mode: 'all',
})
// don't pollute Module
Module._extensions['.js'] = orig
module.exports = function esmRequire(id) {
return _esmRequire(id)
}
@diauweb
Copy link
Author

diauweb commented Sep 21, 2021

OI-wiki/gatsby-oi-wiki/commit/3f782b20263dbe820c1b6eb3baba2b0b53f1ceaf

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment