JavaScript中的“导出默认值”是什么?在默认导出中,导入的命名是完全独立的,我们可以使用任何我们喜欢的名称。
我将用一个简单的例子来说明这一行。
假设我们有三个模块和一个index.html文件:
模块.js模块2.js模块3.js索引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!
因此,更长的解释是:
如果要为模块导出单个对象,则使用“导出默认值”。
因此,重要的是“从'./module3.js'导入blabla”-我们可以改为:
“从'./modul3.js导入pamelanderson”,然后导入pameladerson();。当我们使用“导出默认值”时,这将很好地工作,基本上就是这样-它允许我们在默认值时随意命名它。
P.S.:如果你想测试这个示例-首先创建文件,然后在浏览器中允许CORS->如果你使用Firefox,请在浏览器的URL中键入:about:config->搜索“privacy.file_unique_origin”->将其更改为“false”->打开index.html->按F12打开控制台并查看输出->享受并不要忘记将CORS设置返回默认值。
P.S.2:对不起,变量命名太愚蠢了
更多信息请参见link2medium和link2mdn。