如何在 CakePHP 4 中使用 sortable js 库?

How can I use the sortablejs library in CakePHP4?

我正在尝试将 sortablejs 与 CakePHP4 一起使用,我先阅读了自述文件。

所以,要安装它,请使用 npm install sortablejs --save 要安装它,我发现了一些对 运行 说的东西。

所以我去了 cd cake_project/webroot/js 和 运行 npm install storablejs --save

两个目录 node_modulespackage-lock.json 现在安装在 webroot/js

所有层次结构都在下面。

/node_modules
    |
    |- /sortablejs
      |- LICENSE
      |- package.json
      |- /dist
          |- sortable.umd.js
          |- sortable.umd.js.map
      |- /modular
          |- sortable.complete.esm.js
          |- sortable.compsle.esm.js.map
          |- sortable.core.esm.js
          |- sortable.esm.js
          |- sortable.esm.js.map

我完全按照 README 所说的做了。 我将以下内容放在 template/view.php.


<ul id="items">
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
</ul>

<?= $this->Html->script('view', ['block' => true]) ?>

接下来,我将以下内容添加到 webroot/js/veiw.js

import Sortable from "sortablejs";

let el       = document.getElementById("items");
let sortable = Sortable.create(el);

然后我在 DevTools 的控制台中收到一条错误消息说 Uncaught SyntaxError: Cannot use immport statemnt outside a module view.js:1

import Sortable from 'node_modules/sortablejs';

// ...

检查控制台日志。 Uncaught SyntaxError: Cannot use import statement outside a module view.js:1。 我得到了完全相同的错误。

我查看了 DevTools js 目录 Sources 并注意到 sortablejs 不存在。

template/view.php的最后一行,在template/view.php的最后一行添加<? = $this->Html->script('node_modules/sortablejs', ['block' => true]) ? >

我调用了一个名为 node_modules.js 的不存在的文件。所以,<? = $this->Html->script('node_modules/sortablejs/, ['block' => true]) ? >。现在调用 node_modules/sortablejs/.js

很抱歉。我无能为力了。 我应该怎么办? 请帮助我。

首先,并非所有浏览器都支持 JavaScript modules,因此除非您知道您只针对支持它们的浏览器,否则您不能使用 import 语法,并且作为错误消息指出,它必须在模块本身中使用。

由于您还不熟悉所有这些东西,ES6、模块、捆绑器等,您现在可能想使用 UMD 库,它可以在没有任何导入等的情况下使用。

假设 node_modules 文件夹在您的 webroot 文件夹中,UMD 库的正确路径应该是完整的相对根目录 URL,例如:

/node_modules/sortablejs/dist/sortable.umd.js
$this->Html->script('/node_modules/sortablejs/dist/sortable.umd.js', ['block' => true])

然后就可以直接使用库了,就像首页the examples中的一样:

new Sortable(swapDemo, {
    swap: true, // Enable swap plugin
    swapClass: 'highlight', // The class applied to the hovered swap item
    animation: 150
});

我建议将模块安装在 webroot 文件夹之外,然后将它们复制或符号链接到您的 webroot 文件夹中,最好是作为构建脚本的一部分。

GitHub 存储库中的示例最有可能用于与 Webpack 等捆绑器的上下文中,这些捆绑器将解析导入。在浏览器中使用模块看起来会有点不同,像这样:

<script type="module">
    import Sortable from '/node_modules/sortablejs/modular/sortable.complete.esm.js';
    
    const el = document.getElementById('items');
    const sortable = Sortable.create(el, {
        swap: true, // Enable swap plugin
        swapClass: 'highlight', // The class applied to the hovered swap item
        animation: 150
    });
</script>