Last active
March 22, 2022 18:42
-
-
Save sdesalas/0b66f15772f119a2dd911d0799047122 to your computer and use it in GitHub Desktop.
ESM in extensionless executable files (`import` statement inside dependency chain)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
console.log('Loading `./test_lib_dep.js` (internal dependency)..'); | |
const dep = require('./test_lib_dep.js'); | |
module.exports = dep; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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)); |
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
This is the output I get when running this example:
Node versions:
v14.16.0
v16.13.2