Home > front end >  Vue3 Component doesn't render in production when using v-bind:href require()
Vue3 Component doesn't render in production when using v-bind:href require()

Time:05-11

Everything works fine when developing but once I export for production 1 component doesn't render and instead gets replaced by <!--->

After some debugging, I discovered that this happens because of require()

I have images with dynamic URLs that look like this:

:src="require(`@/assets/path/${variable}`)"

This works in dev but once I build the app for production the component doesn't render.

When I replace the path with

src="@/assets/path/file.png"

The component shows up and works properly

Is it something that I can provide to webpack in vue.config.js?

Is there a way to use variables in path without require()?

CodePudding user response:

The expression inside v-bind is executed at runtime, webpack aliases at compile time.

Move require() from html template to data() and it should work in production.

Simple example:

<template>
<img :src="getImg" />
</template>

<script>
export default {
    name: 'Example',
    data() {
        return {
            file: 'image',
        }
    },
    methods: {
        getImg() {
            return require(`@/assets/images/${this.file}.png`)
        },
    },
}
</script>
  • Related