JavaScript の「エクスポートのデフォルト」とは何ですか?
デフォルトのエクスポートでは、インポートの命名は完全に独立しており、好きな名前を使用できます。
この行を簡単な例で説明します。
3 つのモジュールと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;
modul3.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.jspamelanderson();
から pamelanderson をインポート」してから. これは、'export default' を使用すると問題なく動作し、基本的にはこれで終わりです。これにより、default のときに好きな名前を付けることができます。
PS: 例をテストする場合 - 最初にファイルを作成し、次にブラウザでCORSを許可します -> Firefox を使用している場合は、ブラウザの URL に「about:config」と入力します -> 「privacy.file_unique_origin」を検索します - > 「false」に変更します -> index.html を開きます -> F12 を押してコンソールを開き、出力を確認します -> 楽しんで、CORS 設定をデフォルトに戻すことを忘れないでください。
PS2: ばかげた変数名でごめんなさい
詳細はlink2mediumおよびlink2mdnにあります。