Skip to content

Instantly share code, notes, and snippets.

@forivall
Created February 1, 2024 02:03
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 forivall/6668836f1fbc838678167fa7288e13b9 to your computer and use it in GitHub Desktop.
Save forivall/6668836f1fbc838678167fa7288e13b9 to your computer and use it in GitHub Desktop.
esm/cjs module bootstrap
async function main() {
console.log('main');
}
(async function () {
if ('undefined' !== typeof module) {
return require.main === module && main();
}
// eslint-disable-next-line no-new-func
const meta: ImportMeta = new Function('import.meta')();
const process = await import('process');
const { createRequire } = (await import('module')).Module;
const scriptPath = createRequire(meta.url).resolve(process.argv[1]);
const modulePath = (await import('url')).fileURLToPath(meta.url);
const { extname } = await import('path');
const extension = extname(scriptPath);
let isMain: boolean;
if (extension) {
isMain = modulePath === scriptPath;
} else {
const moduleExt = extname(modulePath);
isMain = modulePath.slice(0, -moduleExt.length) === scriptPath;
}
return isMain && main();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment