简体   繁体   中英

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 }

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 } .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM