简体   繁体   English

在 ES6 与 CommonJS 模块中共享 state

[英]Shared state in ES6 vs CommonJS modules

I can share state via CommonJS modules, but not via ES6 modules.我可以通过 CommonJS 模块共享 state,但不能通过 ES6 模块。

I'm wondering why, and want to know how to share state via ES6 modules.我想知道为什么,想知道如何通过 ES6 模块共享 state。

CommonJS通用JS

main.js:主.js:

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

child.js:孩子.js:

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

shared.js:共享.js:

module.exports = {val:1};

Result:结果:

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

ES6 ES6

main.mjs:主.mjs:

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

child.mjs:孩子.mjs:

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

shared.mjs:共享.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.您可以用完全相同的方式分享 state。

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 } .他们都会有{ val: 2 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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