loading...

Unable to use global variables with es6 imports in node

projectescape profile image Aniket ・1 min read

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

Discussion

markdown guide
 

Create a require that just has a {} on it and use that as your global:

//context.js
const context={}
module.exports = {context}
//someModule.js
const {context} = require('./context');
if(context.foo) {
   context.foo();
}
//oh-look-more-code.js
const {context} = require('./context');
context.foo = ()=>console.log("Yep");

//something.mjs
import * as Context from 'context'
Context.context.foo && Context.context.foo()

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!!