DEV Community

Aniket
Aniket

Posted on

Unable to use global variables with es6 imports in node

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)

Collapse
 
miketalbot profile image
Mike Talbot ⭐ • Edited

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

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

Enter fullscreen mode Exit fullscreen mode
//something.mjs
import * as Context from 'context'
Context.context.foo && Context.context.foo()
Enter fullscreen mode Exit fullscreen mode

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.

Collapse
 
projectescape profile image
Aniket

Thanks a lot!!
This is perfect!!