什么是 JavaScript 中的“导出默认值”?
在默认导出中,导入的命名是完全独立的,我们可以使用任何我们喜欢的名称。
我会用一个简单的例子来说明这条线。
假设我们有三个模块和一个 index.html 文件:
- modul.js
- modul2.js
- modul3.js
- index.html
文件 modul.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' 时,这将正常工作,基本上就是这样 - 它允许我们在默认情况下随意命名它。
PS:如果你想测试这个例子 - 先创建文件,然后在浏览器中允许CORS -> 如果你使用的是 Firefox,在浏览器的 URL 中输入:about:config -> 搜索“ privacy.file_unique_origin" -> 将其更改为 "false" -> 打开 index.html -> 按 F12 打开控制台并查看输出 -> 享受并不要忘记将 CORS 设置恢复为默认设置。
P.S.2:对不起,愚蠢的变量命名
更多信息在link2medium和link2mdn。