Skip to content

Instantly share code, notes, and snippets.

@sdesalas
Last active March 22, 2022 18:42
Show Gist options
  • Save sdesalas/0b66f15772f119a2dd911d0799047122 to your computer and use it in GitHub Desktop.
Save sdesalas/0b66f15772f119a2dd911d0799047122 to your computer and use it in GitHub Desktop.
ESM in extensionless executable files (`import` statement inside dependency chain)
#!/usr/bin/env node
/**
* This is a POC of https://github.com/nodejs/modules/issues/152#issuecomment-1068515887
*
* The requires statement below should fail with an error while
* using an ESM import buried inside the module dependency chain:
* import crypto from 'crypto';
* ^^^^^^
* SyntaxError: Cannot use import statement outside a module
*/
console.log('Running `./test_bin` (extensionless binary)..');
console.log('Loading `./test_lib.js` (internal library)..');
const app = require('./test_lib.js');
console.log('Loading `./test_lib_dep.js` (internal dependency)..');
const dep = require('./test_lib_dep.js');
module.exports = dep;
/**
* This dependency is buried several levels deep inside the module depdendency chain
* thus highlighting the fact that ESM `import` statements cannot always be controlled
* by the calling code.
*/
import crypto from 'crypto';
console.log('Printing some random bytes: %s', crypto.randomBytes(10));
@ljharb
Copy link

ljharb commented Mar 22, 2022

Right, but that's because test_lib.js is CJS, so test_lib_dep needs to have an .mjs extension.

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