我试图在CakePHP4中使用sortablejs,并且我首先阅读了ReadMe。
所以,要安装它,使用npm install sortablejs --save
来安装它,我找到了要运行的东西。
所以我去了cd cake_project/webroot/js
并经营npm install storablejs --save
。
node_modules
和package-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
我照自述的话做了。我把下面的内容放在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
。我也犯了同样的错误。
我查看了js
目录中的DevTools 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
。
真对不起。我无能为力了。我该怎么办?请帮帮我。
发布于 2020-12-14 17:40:18
首先,并不是所有浏览器都支持,所以除非您知道只针对支持它们的浏览器,否则不能使用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])
然后您可以直接使用库,就像主页上的一样:
new Sortable(swapDemo, {
swap: true, // Enable swap plugin
swapClass: 'highlight', // The class applied to the hovered swap item
animation: 150
});
我建议在webroot文件夹之外安装模块,然后将它们复制或符号链接到webroot文件夹中,最好是作为构建脚本的一部分。
GitHub存储库中的示例最有可能用于解决导入的之类的绑定器的上下文中。使用浏览器中的模块看起来有点不同,如下所示:
<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>
https://stackoverflow.com/questions/65291240
复制相似问题