I'm trying to break up a giant JavaScript file into smaller files for easier maintainability. It looks something like this:
(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);
I moved all the code out into separate files and replaced each block of code with an import to that file, now the huge JS file looks like this:
(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);
When compiling this file Gulp throws the following error:
'import' and 'export' may only appear at the top level
How to use imports within an immediately invoked function expression?
Technically import
can be used within an IIFE. Though to achieve the expected result you can use import
at the top of a <script type="module">
then pass the references to the 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.