Created
September 21, 2021 01:48
-
-
Save diauweb/f9f7be271ecc7bc0aecaf3dc891e18d2 to your computer and use it in GitHub Desktop.
Requiring a ES Module into CJS environment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OI-wiki/gatsby-oi-wiki/commit/3f782b20263dbe820c1b6eb3baba2b0b53f1ceaf