【问题标题】:Can't include the Cropper.js module into my code无法将 Cropper.js 模块包含到我的代码中
【发布时间】:2020-07-02 07:27:29
【问题描述】:

为了向我的一个 Flask/Jinja 页面添加图像裁剪支持,我关注了 GitHub 上的 Cropper.js usage example,将 CSS 链接添加到我的 HTML 页面的 <head> 并将以下内容添加到我的页面的 <body>

<script src="/static/assets/js/plugins/cropper.min.js" type="module"></script>
<script>
    import Cropper from "cropperjs";

    const image = document.getElementById('crop_image');
    const cropper = new Cropper(image, {
        aspectRatio: 1 / 1,
        crop(event) {
            console.log(event.detail.x);
            console.log(event.detail.y);
            console.log(event.detail.width);
            console.log(event.detail.height);
            console.log(event.detail.rotate);
            console.log(event.detail.scaleX);
            console.log(event.detail.scaleY);
        },
    });
</script>

可以找到cropper.min.js 文件,正如我在 Firefox 77.0.1 浏览器控制台中看到的那样。
但是,我确实在控制台中收到以下错误消息:

SyntaxError: import declarations may only appear at top level of a module

在JS的第一行&lt;script&gt;

import Cropper from "cropperjs";

我发现here in this SO thread 这个错误可能是由于缺少type="module" 而出现在 Firefox 中,但正如您所见,我的代码中确实有这个错误。任何其他想法这里可能有什么问题?

【问题讨论】:

  • 您在哪个浏览器中试用?
  • @Charlie 正如我的帖子所述:Firefox 77.0.1

标签: javascript cropperjs


【解决方案1】:

我遇到了同样的问题。这样就解决了。

将整个包(及其所有依赖项)安装在您选择的静态文件夹中很重要。这应该安装整个包:

npm install cropperjs

从这个包的 dist 文件夹调用模块将确保调用它的所有依赖项。因此,我脑子里有以下内容:

<link rel="stylesheet" href="{% static 'styles/cropperjs/dist/cropper.css' %}">

这在脚本部分:

<script type="text/javascript" src="{% static 'styles/cropperjs/dist/cropper.js' %}"></script>

此外,就像@Matthias 建议的那样,您不需要 import 语句,无论是内联脚本还是不同的 JS 文件。

【讨论】:

    【解决方案2】:

    外部脚本上有type=module,但由于存在导入而失败的脚本上没有,type=module 没有。

    所以

    <script type="module">
        import Cropper from "cropperjs";
    

    应该做的伎俩

    【讨论】:

    • 这样做会导致 Firefox 控制台出现以下错误:“TypeError: Error resolve module specifier:cropperjs
    • 我只是在复制你的代码。对于模块名称,请查看其声明。该错误表明cropperjs 不是cropper.min.js 中声明的模块
    • 快速查看库文档后,我猜你必须导入 cropper.esm.js (ES Module)
    【解决方案3】:

    好的,终于找到解决方案了。 记录:

    我需要从 JS 脚本链接中删除 type="module" 部分,并且还要删除 import Croppe 行。将两者都删除后,它现在可以工作了。

    【讨论】:

      猜你喜欢
      • 2018-07-15
      • 2018-05-27
      • 1970-01-01
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 2017-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多