What does it mean by live bindings?

怎甘沉沦 提交于 2021-02-20 08:33:07

问题


I am following a tutorial and it says

ES modules uses live bindings. It means a feature to support cyclical dependencies.

But I don't clearly understand this concept. What does this mean?


回答1:


Live bindings is a concept introduced in ES modules. It means that when the exporting module changes a value, the change will be visible from the importer side. This is not the case for CommonJS modules. Module exports are copied in CommonJS. Hence importing modules cannot see changes happened on the exporter side.


ESM

counter.mjs

export let count = 1;
export function increment() {
    ++count;
}

index.mjs

import { count, increment } from './counter.mjs';
console.log(count);
increment();
console.log(count);

Output

$ node --experimental-modules index.mjs
1
2

CJS

counter.js

let count = 1;
function increment() {
    ++count;
}

exports.count = count;
exports.increment = increment;

index.js

const { count, increment } = require('./counter.js');
console.log(count);
increment();
console.log(count);

Output

$ node index.js
1
1

More resources on the topic:

  • What do ES6 modules export? by Axel Rauschmayer
  • ES modules: A cartoon deep-dive by Lin Clark
  • Chapter on Modules in Exploring JS by Axel Rauschmayer


来源:https://stackoverflow.com/questions/52211309/what-does-it-mean-by-live-bindings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!