1

// env.development.js

module.exports = {
  fileName: 'banner_dev.png'
}

// env.production.js

module.exports = {
  fileName: 'banner_prod.png'
}

// index.vue

<script>
import bannerSrc from '@/assets/img/' + process.env.fileName

export default {
  data () {
    return {
      banner: {
        src: bannerSrc,
      }
    }
  },
</script>

Hello, I'm new to Nuxt js. I would like to import an image file dynamically with using env value when build it. However, I get error at below.

import bannerSrc from '@/assets/img/' + process.env.fileName

Is it possible to import image file dynamically with using env file? If possible is there work around for it? Thanks!

shinyatk
  • 855
  • 11
  • 28

1 Answers1

0

Yes you can.

Follow these steps:

1 - define your var in a .env file:

IMAGE=lama

2 - Add the environment var in your nuxt.config.js file:

{
  publicRuntimeConfig: {
    image: process.env.IMAGE
  },
}

3 - Call it in a vue.js file:

<img
  :src="require(`~/assets/images/${$config.image}.jpg`)"
  style="width: 250px; height: 200px"
/>

Here is a codesand box: https://codesandbox.io/s/nuxtjs-load-image-dynamically-with-environment-variable-e3xgf

Have fun! :)

ThisIsMyName
  • 887
  • 7
  • 14