如何在IIFE中使用es6导入?

时间:2019-02-11 18:21:27

标签: javascript ecmascript-6

我正试图将一个巨大的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

如何在立即调用的函数表达式中使用导入?

1 个答案:

答案 0 :(得分:1)

从技术上讲,import可以在IIFE中使用。尽管要获得预期的结果,您可以在import顶部使用<script type="module">,然后将引用传递给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>