首页 > 解决方案 > React-Image-Annotate - SyntaxError:无法在模块外使用导入语句

问题描述

我正在尝试使用react-image-annotate但是当我第一次尝试设置它时它给了我这个问题。

在此处输入图像描述

这是我使用它的方式:

import React from 'react'
import ReactImageAnnotate from 'react-image-annotate'

function ImageAnnotator() {
    return (
        <ReactImageAnnotate
            selectedImage="https://images.unsplash.com/photo-1561518776-e76a5e48f731?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80"
            // taskDescription="# Draw region around each face\n\nInclude chin and hair."
            // images={[
            //     { src: 'https://example.com/image1.png', name: 'Image 1' },
            // ]}
            // regionClsList={['Man Face', 'Woman Face']}
        />
    )
}

export default ImageAnnotator

如果这很重要,我正在使用 Next.js

更新 1 我尝试按照 Alejandro Vales 的建议使用这个babel 插件。它给出了与以前相同的错误。这是babel我的关键package.json

    "babel": {
        "presets": [
            "next/babel"
        ],
        "plugins": [
            [
                "@babel/plugin-proposal-decorators",
                {
                    "legacy": true
                }
            ],
            [
                "@babel/plugin-transform-modules-commonjs",
                {
                    "allowTopLevelThis": true
                }
            ]
        ]
    }

标签: javascriptreactjsnext.js

解决方案


我会说这个问题依赖于图书馆本身,他们在这里回复的内容(类似的错误)https://github.com/UniversalDataTool/react-image-annotate/issues/90#issuecomment-683221311

事实上,我想说的一种解决方法imports是将 babel 添加到项目中,这样您就可以将项目中的转换为require自动,而无需更改整个项目的代码。

这是您正在寻找的 babel 包https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs

造成这种情况的另一个原因可能是您的软件包版本过时,因为有些人报告说在使用较新版本的Create React App( https://github.com/UniversalDataTool/react-image-annotate/issues/37#issuecomment- 607372287 )

您可以做的另一个修复(取决于您的资源有点疯狂)是分叉库,创建库的 CJS 版本,然后将其推送到库,以便您和其他任何人将来都可以使用它。


推荐阅读