React中的Import()-在Chrome / Firefox扩展中引发错误

时间:2019-01-29 11:27:08

标签: javascript reactjs google-chrome-extension firefox-addon

我有一个在localhost上运行的React应用程序。我正在使用import()方法来动态获取一些图片。这是一个获取图片URL并将其存储在state中的循环。该代码非常基本:

componentDidMount() {
  this.fetchPictures(items)
}

fetchPictures = (items) => {
  let imp = import(`path/whatever/items.path.png`)
    .then( image => {
       this.setState({
         images: [...images, image]
       })
    })
}

(为简化起见,我将其简化并省略了循环部分)

非常基础的东西,在localhost上效果很好。但是,我要构建的是浏览器扩展,在其中,扩展到import()的位置并向我报告错误:

TypeError: undefined is not a function
at Array.map (<annonymus>)
at r (.png$:22)
...

我已将import()放在try-catch中,是的,确实是问题所在。

有人可以告诉我什么可能导致此问题吗?对于Chrome和Firefox,这是相同的错误。

1 个答案:

答案 0 :(得分:2)

您可以使用

之类的导入
import mainLogo from'path/whatever/items.path.png';

您也可以使用require渲染图像,例如

fetchPictures = (items) => {
let imp = require('path/whatever/items.path.png')
.then( image => {
   this.setState({
     images: [...images, image]
   })
})

}