Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
Shared state in ES6 vs CommonJS modules

I can share state via CommonJS modules, but not via ES6 modules.

I'm wondering why, and want to know how to share state via ES6 modules.

CommonJS

main.js:

const shared = require('./shared.js');
shared.val = 2;
require('./child.js');
console.log('main.js', shared);

child.js:

const shared = require('./shared.js');
console.log('child.js', shared);

shared.js:

module.exports = {val:1};

Result:

$ node main.js
child.js { val: 2 }
main.js { val: 2 }

ES6

main.mjs:

import shared from './shared.mjs';
shared.val = 2;
import a from './child.mjs';
console.log('main.mjs', shared);

child.mjs:

import shared from './shared.mjs';
console.log('child.mjs', shared);
export default undefined;

shared.mjs:

export default {val:1};

Result:

$ node main.mjs
child.mjs { val: 1 }
main.mjs { val: 2 }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can share state in exactly the same way.

What you can't though is run code in between imports. They all should be at the top of your file because they are basically hoisted to the top.

If you change child to something like this:

import shared from './shared.mjs';

export default () => {
  console.log('child', shared);
};

And then run that after you've changed shared:

import shared from './shared.mjs';
import runChild from './child.mjs';

shared.val = 2;

console.log('main', shared);
runChild();

They'll both have { val: 2 }.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!