The issue lies in the absence of information regarding the module's location, which poses a challenge for webpack in resolving it.
Using a completely dynamic import statement like import(foo) is not feasible because foo could potentially point to any file or path within the system or project.
The import() function must include some level of detail about the module's location.
To address this, a BaseImage component can be created to replace dynamically sourced content starting with a specific path, in this scenario ../assets/
, enabling webpack to pre-emptively understand this information.
For example:
<template>
<img
:src="computedSrc"
:alt="alt"
class="BaseImage"
v-bind="$attrs"
v-on="$listeners"
/>
</template>
<script>
export default {
name: 'BaseImage',
inheritAttrs: false,
props: {
src: {
type: String,
required: true,
},
/**
* The alt tag is required for accessibility and SEO purposes.
*
* If it is a decorative image, which is purely there for design reasons,
* consider moving it to CSS or using an empty alt tag.
*/
alt: {
type: String,
required: true,
},
},
computed: {
// If the URL starts with ../assets/, it will be interpreted as a module request.
isModuleRequest() {
return this.src.startsWith('../assets/')
},
computedSrc() {
// If it is a module request,
// the exact module is not known on compile time,
// so an expression is used in the request to create a context.
return this.isModuleRequest
? require(`../assets/${this.src.replace('../assets/', '')}`)
: this.src
},
},
}
</script>
Swap out img
for the BaseImage
component.
<BaseImage :src="img.src" :alt="img.alt"/>