I'm building a CLI that injects some variables into the imported packages for them to use. Normally, I would do something like this
const foo=()=>{
console.log("Hello World");
}
global.foo=foo;
require('./index.js')
Where index.js is
if(global.foo){
global.foo();
}
But since the latest version of node also supports .mjs
files that enables es6 imports, this approach won't work as es6 imports don't have access to global.
I cannot use process.env
as I want to share functions too and add listeners to the variables.
Any help would be appreciated
Top comments (2)
Create a require that just has a {} on it and use that as your global:
Bear in mind that in ES6 all imports are hoisted, so you will need to configure foo in an import or before all of this code executes. Can't have it inline like in cjs.
Thanks a lot!!
This is perfect!!