简体   繁体   English

Webpack无法解析JS变量提供的路径

[英]Webpack not resolving paths supplied by JS variable

I'm making an app with vue and ionic, but when trying to load assets the paths are not resolving. 我正在使用vue和ionic制作一个应用程序,但是当尝试加载资产时,路径无法解析。

<template>
    <div id="index">

        <img :src="image.src" v-for="image in images">

    </div>
</template>

<script>
export default {

    name: 'Inicio',

    data() {
        return {
            images: [
                {src: '@/assets/xxx.png'},
                {src: '@/assets/xxxx.png'},
                {src: '@/assets/xxx.png'}
            ]
        }
    }
}
</script>

The path in the src attribute appears like the one typed in the var '@/assets/xxx.png' . src属性中的路径看起来像在var '@/assets/xxx.png'键入的路径。

But if I do it directly, by typing the src in the image manually, like <img src="@/assets/xxx.png"> It loads the image correctly. 但是,如果我直接执行此操作,请在图像中手动键入src,例如<img src="@/assets/xxx.png">它会正确加载图像。

You cannot refer static assets using v-for , since webpack needs to rewrite static paths before runtime. 您不能使用v-for引用静态资产,因为webpack需要在运行时之前重写静态路径。 The values of image.src will only be read and parsed to template at runtime, so there is no compiling from webpack to translate relative paths to real paths in bundle. image.src的值将仅在运行时读取并解析为模板,因此没有从webpack进行编译以将相对路径转换为bundle中的实际路径的情况。

One solution is using require() : 一种解决方案是使用require()

<template>
    <div id="index">

        <img :src="image.src" v-for="image in images">

    </div>
</template>

<script>
export default {

    name: 'Inicio',

    data() {
        return {
            images: [
                {src: require('@/assets/xxx.png') },
                {src: require('@/assets/xxxx.png') },
                {src: require('@/assets/xxx.png') }
            ]
        }
    }
}
</script>

Demo sandbox: https://codesandbox.io/s/811px8kn88 演示沙箱: https : //codesandbox.io/s/811px8kn88

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

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