Can't include the Cropper.js module into my code

Viewed 1971

To add image cropping support to one of my Flask/Jinja pages I followed the Cropper.js usage example on GitHub, added the CSS link to the <head> of my HTML page and added the following to the <body> of my page:

<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>

The cropper.min.js file can be found, as I see in the Firefox 77.0.1 browser console.
However, I do get the following error message in the console:

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

at the first line of the JS <script>:

import Cropper from "cropperjs";

I found here in this SO thread that this error might come in Firefox from missing type="module", but as you can see I do have this in my code. Any other ideas what could be wrong here?

3 Answers

I was having the same issue. This solved it.

Its important to install the entire package (with all its dependencies) in the static folder of your choice. This should install the entire package in its entirety:

npm install cropperjs

Calling the module from the dist folder of this package will ensure all its dependencies are called. Therefore, I have the following in the head:

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

and this in the scripts section:

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

Also, like @Matthias suggested, you don't need the import statement, whether its an inline script or a different JS file.

You have the type=module on the external script but not on the script that fails due to the import being present, and type=module not.

so

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

Should do the trick

Ok, finally found the solutiuon. For the records:

I needed to remove the type="module" part from the JS script link, and also remove the import Croppe line. Having both removed it works now.

Related