DEV Community


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");

Where index.js is


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 (2)

Editor guide
miketalbot profile image
Mike Talbot • Edited

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

const context={}
module.exports = {context}
const {context} = require('./context');
if( {;
const {context} = require('./context'); = ()=>console.log("Yep");

import * as Context from 'context' &&

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.

projectescape profile image
Aniket Author

Thanks a lot!!
This is perfect!!