0

I'm trying to load an image dynamically in Vue like for example:

computed: {
  background () {
    return require('./bgs/' + process.env.VUE_APP_SOME_VAR + '.jpg')
  }
}

However, according to this site (https://vuejs-templates.github.io/webpack/static.html at "Getting Asset Paths in JavaScript") the following will happen:

Note the above example will include every image under ./bgs/ in the final build. This is because Webpack cannot guess which of them will be used at runtime, so it includes them all.

For me, however, this variable is only set once in the environment variables. So it never changes throughout the app. And I don't need al the images that it includes by default. Is it possible to change this behavior by any chance?

Gilian
  • 1,539
  • 2
  • 15
  • 27

1 Answers1

0

I found a nice answer to this using aliases thanks to https://stackoverflow.com/a/53603600/4349566.

I added a new alias to my vue.config.js like so:

module.exports = {
  // Some less important stuff

  configureWebpack: {
    resolve: {
      alias: {
        "~vendor": require("path").resolve(
          __dirname,
          "src/assets/" + process.env.VUE_APP_SOME_VAR
        )
      }
    }
  }
};

And then I could use the require like so: require('~vendor/images/banner-large.jpg'). So now when I'm building, it doesn't include unwanted images.

Gilian
  • 1,539
  • 2
  • 15
  • 27