Skip to content

Instantly share code, notes, and snippets.

@libetl
Created May 6, 2023 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save libetl/d58935904b427d669be43806916c51ee to your computer and use it in GitHub Desktop.
Save libetl/d58935904b427d669be43806916c51ee to your computer and use it in GitHub Desktop.
common-js entrypoint for projects that are only available as ecmascript modules
const Module = require('module')
const orig = Module._extensions['.js']
const fs = require('fs')
const delegateEcmascriptModulePath = '../esm/index.js';
const dependenciesInEcmascriptModulesOnly = [basename(__dirname) + "/esm/", "/del/", "/p-map/"];
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)
// --
return
}
throw e
}
}
require("@babel/register")({
"only": [
(path) => {
return dependenciesInEcmascriptModulesOnly.some(
pattern => path.includes(pattern)
);
}],
"presets": ["@babel/preset-env", "@babel/preset-react"],
"plugins": ["babel-plugin-transform-import-meta"]
});
module.exports = require(ecmascriptModulePath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment