如何在创建 jQuery 插件时使用 ES6 模块?

How to use ES6 modules while creating jQuery plugin?

我正在创建一个 jQuery 插件来构建表单生成器。该代码将非常冗长。我不想将所有内容都保存在一个文件中。 为此,我试图将所有内容分解为 ES6 模块,但 JS 抛出语法错误。

Uncaught SyntaxError: Unexpected identifier

Uncaught TypeError: $(...).formBuilder is not a function

这是我的代码:

index.html

<!DOCTYPE html>
<html>
<head>
  <title>Form Builder</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="style.css">
  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">

  <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/3.0.1/mustache.min.js"></script>

  <!-- <script src="functions.js"></script> -->
  <script src="index.js"></script>
</head>
<body>
    <div id="form-builder"></div>
</body>
</html>
<script type="text/javascript">
    $("#form-builder").formBuilder();
</script>

index.js

import formBuilder from './functions.js'

(function($){
    $.fn.formBuilder = function(){
        formBuilder()
    }
}(jQuery))

functions.js

export default function formBuilder(){
    $.get('template.mst', function(template) {
            let rendered = Mustache.render(template, fieldsData);
            $('#form-builder').html(rendered);
    });
}

我必须进行两项更改才能使您的代码变为 运行(在 Chrome/Firefox 中):

首先,来自MDN

The import statement cannot be used in embedded scripts unless such script has a type="module".

这有点误导:"embedded script" 听起来好像它不包含 src= 脚本...但实际上没有它似乎无法工作。

<script type="module" src="index.js"></script>

其次,模块脚本是延迟加载的,这意味着您的最终 script 标记将在 index.js 实际上是 loaded/parsed 之前执行。您可以使用 jQuery ready 回调来更改它。

<script>
  $(() => {
    $("#form-builder").formBuilder();
  });
</script>