Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The assumption that module does not exist inside ESM context is fundamental wrong. #1145

Closed
frank-dspeed opened this issue Nov 7, 2020 · 2 comments

Comments

@frank-dspeed
Copy link

frank-dspeed commented Nov 7, 2020

I saw a merge with a test like

// Test import builtin modules
import {readFileSync} from 'fs';
if(typeof readFileSync !== 'function') throw new Error('failed to import builtin module')

if(typeof module !== 'undefined') throw new Error('module should not exist in ESM')

And i see no problem with that test at all it is from #1136

but i need to make sure that you no where see that as general rule of thumb module and module.exports do exists inside ESM

here a example CJS loader written in ESM to load CJS inside a browser via esm

async function require(path) {
	let _module = window.module;
	window.module = {};
	await import(path);
	let exports = module.exports;
	window.module = _module; // restore global
	return exports;
}

(async () => { // top-level await cannot come soon enough…

let x = await require("https://cdn.jsdelivr.net/gh/x/lib/index.js");

})();

in nodejs we have directly

import { createRequire } from 'module';

it is importent that you understand that ESM includes everything CJS includes + ESM every node builtin module exists only as CJS version and gets a additional wrapper to be ESM Compatible.

@cspotcode
Copy link
Collaborator

We are not making the assumption that you're describing here. Are you saying that other people are making this incorrect assumption? Is there a question or a bug to report here?

For anyone else coming across this issue, the relevant behavior is described here:
https://nodejs.org/dist/latest-v15.x/docs/api/esm.html#esm_no_require_exports_module_exports_filename_dirname

node does not expose a module object in scope when it loads an ESM module, so the test in question is able to use the absence of module to reliably prove that the file was loaded as ESM instead of CommonJS, since we know within the scope of this test that a module object will not be coming from anywhere else.

@frank-dspeed
Copy link
Author

ok so it is clear i can close it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants