Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Mutable difference between ES6 named and default exports

When importing/exporting data from ES6 modules, mutability of that data appears to be different between named imports and exports. Is there a reason for this or some fundamental difference I'm not understanding?

// counter.js
export let count = 0;

export const incrementCount = () => count += 1;

export default count;
// main-default.js
import count, { incrementCount } from './counter';

console.log(count); // 0

incrementCount();
incrementCount();

console.log(count); // 0
// main-named.js
import { count, incrementCount } from './counter';

console.log(count); // 0

incrementCount();
incrementCount();

console.log(count); // 2

In both scenarios, I would expect count to increment. However, this only happens when using named exports.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The problem is that you used export default count;, which does not export the count binding (allowing aliasing the mutable variable by an import) but actually creates a new, hidden variable that gets the initial value assigned but is never changed afterwards.

export default count;

desugars to

let *default* = count; // where *default* is a guaranteed collision-free identifier
export { *default* as default }

What you want instead is

// counter.js
let count = 0;
export const incrementCount = () => count += 1;
export { count as default }

// main-default.js
import countA, { default as countB, incrementCount } from './counter';

console.log(countA, countB); // 0, 0
incrementCount();
console.log(countA, countB); // 1, 1

See also How can I alias a default import in Javascript?.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...