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));
@sdesalas
Copy link
Author

sdesalas commented Mar 22, 2022

This is the output I get when running this example:

Node versions:

  • v14.16.0
  • v16.13.2
$ ./test_bin 
Running `./test_bin` (extensionless binary)..
Loading `./test_lib.js` (internal library)..
Loading `./test_lib_dep.js` (internal dependency)..
/projects/test_esm_module_dep/test_lib_dep.js:7
import crypto from 'crypto';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1031:15)
    at Module._compile (node:internal/modules/cjs/loader:1065:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/projects/test_esm_module_dep/test_lib.js:4:13)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)

@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