Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

javascript - How to retain 'live binding' with default export

As you may know, in ECMAScript modules exports create a so called live view on a given variable. For example, when we change an exported variable some time later in the code, the change will be visible in modules that import it:

export let x = 1;
x = 2;

-----------

import { x } from "./x.mjs";
console.log(x) // logs 2

But things are a bit different with a default export. A default export is associated with a particular value, not a variable name. So when we do:

let x = 1;
export default x;
x = 2;

---------------------

import x from "./x.mjs";
console.log(x) // logs 1

We get the old value.

How to make default export behave like named export, that is, how to enforce it to be a live view on a given variable?

Playground: glitch.com


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A way to do it:

// x.mjs
let x = 1;
export { x as default }; // this is important to export actual live binding
x = 2;

And then on the other side:

// script.mjs
import test from "./x.mjs";
console.log(test) // will log 2

Another way to do it is with closure, but it will require wrapping of your variable export into a function:

// x.mjs
let x = 1;
export default () => x;
x = 2;
// script.mjs
import { default as _default } from "./x.mjs";
console.log(_default()) // will log 2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...