[英]How to use es6 imports within an IIFE?
我正在嘗試將一個巨大的JavaScript文件分解為多個較小的文件,以實現更易維護的功能。 看起來像這樣:
(function($, document, window) {
var $htmlBody = $("html, body"),
$body = $("body"),
$doc = $(document),
$loc = $(location),
$win = $(window);
// THOUSANDS OF LINES OF CODE HERE...
$doc.ready(function() {
APP.init();
});
})(jQuery, document, window);
我將所有代碼移到了單獨的文件中,並將每個代碼塊替換為對該文件的導入,現在,巨大的JS文件如下所示:
(function($, document, window) {
var $htmlBody = $("html, body"),
$body = $("body"),
$doc = $(document),
$loc = $(location),
$win = $(window);
import "./src/account.js";
import "./src/user.js";
import "./src/shop.js";
// etc etc..
$doc.ready(function() {
APP.init();
});
})(jQuery, document, window);
Gulp編譯此文件時,將引發以下錯誤:
'import' and 'export' may only appear at the top level
如何在立即調用的函數表達式中使用導入?
從技術上講,可以在IIFE中使用import
。 盡管要獲得預期的結果,您可以在<script type="module">
頂部使用import
,然后將引用傳遞給IIFE
<script type="module">
import a from "./src/account.js";
import b from "./src/user.js";
import c from "./src/shop.js";
(function($, document, window, a, b, c) {
// do stuff with `a`, `b`, `c`
var $htmlBody = $("html, body"),
$body = $("body"),
$doc = $(document),
$loc = $(location),
$win = $(window);
$doc.ready(function() {
APP.init();
});
})(jQuery, document, window, a, b, c);
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.