简体   繁体   English

如何在IIFE中使用es6导入?

[英]How to use es6 imports within an IIFE?

I'm trying to break up a giant JavaScript file into smaller files for easier maintainability. 我正在尝试将一个巨大的JavaScript文件分解为多个较小的文件,以实现更易维护的功能。 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: 我将所有代码移到了单独的文件中,并将每个代码块替换为对该文件的导入,现在,巨大的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);

When compiling this file Gulp throws the following error: Gulp编译此文件时,将引发以下错误:

'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. 从技术上讲,可以在IIFE中使用import 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 ,然后将引用传递给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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM