简体   繁体   English

使用 webpack 动态加载图像

[英]Load images dynamically with webpack

I'm running a webpack web app on AWS S3 and I have to dynamically show images.我在 AWS S3 上运行 webpack web 应用程序,我必须动态显示图像。 I found this following code thanks to this post :由于这篇文章,我找到了以下代码:

getImgUrl(nameImage) {
    let images = require.context("../static/images/members/", false, /\.jpg$/);
    return images("./" + nameImage + ".jpg");
}

And in my vuetify template:在我的 vuetify 模板中:

<template v-else-if="activeTab == 0">
    <img
       :src="getImgUrl(chunk[i-1])"
    />
</template>

The problem is the images are not loaded as my aws server returns a 403 Forbidden error strict origin when cross origin.问题是图像未加载,因为我的 aws 服务器在跨源时返回 403 禁止错误严格源。

That's weird because I don't have any problem with another image that I load in my topbar with this code:这很奇怪,因为我用这段代码加载到顶部栏的另一张图片没有任何问题:

<v-img
    :alt="appName"
    class="shrink mr-2"
    contain
   :src="require('../static/images/logo.jpg').default"
   width="40"
   height="40" 
/>

Do you have any other idea how I could require my images dynamically?您是否有任何其他想法我可以动态地要求我的图像?

Nevermind, I just had to add.default to the value to return:没关系,我只需要将 add.default 添加到要返回的值:

getImgUrl(nameImage) {
    let images = require.context("../static/images/members/", false, /\.jpg$/);
    return images("./" + nameImage + ".jpg").default;
}

Remember kids: if require() doesn't work, just add.default at the end #SuperSmart记住孩子们:如果 require() 不起作用,只需在末尾添加.default #SuperSmart

To be true I didn't understand why I had to do this, but if you know feel free to tell me in the comments说实话,我不明白为什么我必须这样做,但如果你知道,请随时在评论中告诉我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM