繁体   English   中英

在 ES6 与 CommonJS 模块中共享 state

[英]Shared state in ES6 vs CommonJS modules

我可以通过 CommonJS 模块共享 state,但不能通过 ES6 模块。

我想知道为什么,想知道如何通过 ES6 模块共享 state。

通用JS

主.js:

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

孩子.js:

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

共享.js:

module.exports = {val:1};

结果:

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

ES6

主.mjs:

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

孩子.mjs:

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

共享.mjs:

export default {val:1};

结果:

$ node main.mjs
child.mjs { val: 1 }
main.mjs { val: 2 }

您可以用完全相同的方式分享 state。

但您不能在导入之间运行代码。 它们都应该在你的文件的顶部,因为它们基本上被提升到顶部。

如果你把孩子改成这样:

import shared from './shared.mjs';

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

然后在更改共享后运行它:

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

shared.val = 2;

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

他们都会有{ val: 2 }

暂无
暂无

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

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