JavaScript 中的“导出默认值”是什么?
在默认导出中,导入的命名是完全独立的,我们可以使用任何我们喜欢的名称。
我将用一个简单的例子来说明这条线。
假设我们有三个模块和一个index.html文件:
- 模块.js
- 模块2.js
- 模块3.js
- 索引.html
文件模块.js
export function hello() {
console.log("Modul: Saying hello!");
}
export let variable = 123;
文件modul2.js
export function hello2() {
console.log("Module2: Saying hello for the second time!");
}
export let variable2 = 456;
模块3.js
export default function hello3() {
console.log("Module3: Saying hello for the third time!");
}
文件index.html
<script type="module">
import * as mod from './modul.js';
import {hello2, variable2} from './modul2.js';
import blabla from './modul3.js'; // ! Here is the important stuff - we name the variable for the module as we like
mod.hello();
console.log("Module: " + mod.variable);
hello2();
console.log("Module2: " + variable2);
blabla();
</script>
输出是:
modul.js:2:10 -> Modul: Saying hello!
index.html:7:9 -> Module: 123
modul2.js:2:10 -> Module2: Saying hello for the second time!
index.html:10:9 -> Module2: 456
modul3.js:2:10 -> Module3: Saying hello for the third time!
所以更长的解释是:
如果要为模块导出单个事物,则使用“导出默认值”。
所以重要的是“从'./modul3.js'导入blabla ”——我们可以说:
“从 './modul3.js” 导入pamelanderson,然后pamelanderson();
. 当我们使用 'export default' 时,这会很好地工作,基本上就是这样 -它允许我们在它是 default 时随意命名它。
PS:如果您想测试示例 - 先创建文件,然后在浏览器中允许CORS -> 如果您使用的是 Firefox,请在浏览器的 URL 中键入:about:config -> 搜索“privacy.file_unique_origin” - > 将其更改为“false” -> 打开 index.html -> 按 F12 打开控制台并查看输出 -> 享受并且不要忘记将 CORS 设置恢复为默认值。
PS2:对不起,愚蠢的变量命名
更多信息在link2medium和link2mdn中。