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.
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 }
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 }
Read more here: Source link