Search code examples
javascriptnuxt.jsrequire

JavaScript Require From Variable


I'm using the following:

props: {
    backgroundImagePath: {
        type: String,
        required: true,
        default: '@/static/images/9.jpeg'
    }
}

:style="{
    backgroundImage: `url(${require(backgroundImagePath)})`
}"

Which gives me the following error:

Cannot find module '@/static/images/9.jpeg'

:style="{
    backgroundImage: `url(${require('@/static/images/9.jpeg')})`
}"

Works as normal however - I'm not sure why?

For context I'm using NuxtJS.


Solution

  •  props: {
        backgroundImagePath: {
            required: true,
            default: require('@/static/images/9.jpeg')
        }
     }
    
     :style="{
         backgroundImage: `url(${backgroundImagePath})`
     }"
    

    Changing the backgroundImagePath prop default value seemed to resolve this.