Let's say I have a variable that I want to export. What's the difference between
export const a = 1;
vs
export let a = 1;
I understand the difference between const
and let
, but when you export them, what are the differences?
Let's say I have a variable that I want to export. What's the difference between
export const a = 1;
vs
export let a = 1;
I understand the difference between const
and let
, but when you export them, what are the differences?
在 ES6 中,import
s 是导出值的实时只读视图。结果,当您这样做时,无论您在模块中如何声明import a from "somemodule";
,都无法分配给。a
a
但是,由于导入的变量是实时视图,它们确实会根据导出中的“原始”导出变量而改变。考虑以下代码(从下面的参考文章中借用):
//------ lib.js ------
export let counter = 3;
export function incCounter() {
counter++;
}
//------ main1.js ------
import { counter, incCounter } from './lib';
// The imported value `counter` is live
console.log(counter); // 3
incCounter();
console.log(counter); // 4
// The imported value can’t be changed
counter++; // TypeError
如您所见,区别实际上在于lib.js
,而不是main1.js
。
总结一下:
import
无论您如何在模块中声明相应的变量,都不能分配给-ed 变量。let
-vs-const
语义适用于模块中声明的变量。
const
,则不能在任何地方重新分配或重新分配它。let
,则只能在模块中重新分配(而不是用户)。如果它改变了,import
-ed 变量也会相应地改变。我认为一旦你导入它,行为是相同的(在你的变量将在源文件之外使用的地方)。
唯一的区别是如果您尝试在此文件结束之前重新分配它。