DEV Community

Discussion on: Unable to use global variables with es6 imports in node

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