其他分享
首页 > 其他分享> > vue 前端 require动态引入图片报错Error: Cannot find module

vue 前端 require动态引入图片报错Error: Cannot find module

作者:互联网

在Vue中,Image组件的source如果使用require方式引入图片资源,则必须使用静态的字符串,不能使用变量,因为require是编译时执行的,而非运行时执行!

于是Vue为Image组件的source提供了另外一种使用变量的方式source={{ uri: item.picture }},也支持如下写法:

let source = '';
  switch (item.resultType) {
    case 0:
      source = require('../../assets/app/ic_dsh.png')
      break;
    case 1:
      source = require('../../assets/app/ic_sptg.png')
      break;
    case 2:
      source = require('../../assets/app/ic_bohui.png')
      break;
    case 3:
      source = require('../../assets/app/ic_zuofei.png')
      break;
  }
<Image
          style={{
            position: 'absolute',
            zIndex: 10,
            top: OASize(0),
            right: OASize(5),
            width: OASize(44),
            height: OASize(16),
          }}
          // resizeMode="contain"
          source={source}

/>

 

 

下面来说说ES6的require

关于es6的require添加动态变化的路径

直接静态写死是不会有错误的:

let imgUrl = require('../images/a.png');

但是如果你尝试着:

var imgUrl = "../images/b.jpg";

let img = require(imgUrl);

或者这样动态变化:

require(`../../assets/images/${showAllExpended?'unfold':'up'}.png`

那就只能凉凉的报错咯(因为require它是打包工具所需要的标识,你搞成运行时通过变量去定义的话,它就没办法打包了啊):

PS:由于我浏览器缓存我复现不了情况,就取一张别人的报错图片来解释一下吧:

 

 

解决方法:​

 

而require里的正确的格式必须是path

可以这么写:

var imgUrl = "a";

let img = require('../images/'+imgUrl+'.jpg');

当然最好这么写:imgUrl 为图片名称即可,相对路径与绝对路径不能加。

var imgUrl = "b.jpeg";

let img = require('../images/'+imgUrl);

 

TRANSLATE with x English
Arabic Hebrew Polish
Bulgarian Hindi Portuguese
Catalan Hmong Daw Romanian
Chinese Simplified Hungarian Russian
Chinese Traditional Indonesian Slovak
Czech Italian Slovenian
Danish Japanese Spanish
Dutch Klingon Swedish
English Korean Thai
Estonian Latvian Turkish
Finnish Lithuanian Ukrainian
French Malay Urdu
German Maltese Vietnamese
Greek Norwegian Welsh
Haitian Creole Persian  
  TRANSLATE with COPY THE URL BELOW Back EMBED THE SNIPPET BELOW IN YOUR SITE Enable collaborative features and customize widget: Bing Webmaster Portal Back

标签:vue,..,require,module,source,报错,png,let,imgUrl
来源: https://www.cnblogs.com/lyj0810/p/16341084.html