Dynamically loading assets with require() that might not exist in webpack + VueJS Dynamically loading assets with require() that might not exist in webpack + VueJS vue.js vue.js

Dynamically loading assets with require() that might not exist in webpack + VueJS


This is a common request and latest WebPack, AFAIK (and I just searched for it again), does not expose an API for especifically testing the existence of a module.

In other words, you'd have to handle the uncertainty of the loading yourself. Example:

  computed: {    imageSrc () {      if (this.coinData.symbol) {        try {          return require('../statics/icons/svg/' + this.coinData.symbol + '.svg')        } catch (e) {          if (e.name !== "ModuleNotFoundError") throw e; // handle false-positives          // in cordova, use the line below instead of the above          // if (!e.message.startsWith('Cannot find module')) throw e;          return require('../statics/icons/svg/fallback.svg');        }      }      return require('../statics/icons/svg/fallback.svg');    }  }

This way I'd argue you wouldn't even need a fallback src in the template. You could return it in the computed property itself.