问题是没有关于模块所在位置的信息,webpack无法解析。
不可能使用完全动态的导入语句,例如
进口(富)。因为 foo 可能是任何文件的任何路径
您的系统或项目。
import() 必须至少包含一些关于
模块所在位置。
要解决此问题,您可以创建一个 BaseImage 组件来替换以特定路径开头的动态源,在本例中为 ../assets/,并让 webpack 事先知道该信息。
即。
<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>
将img 替换为BaseImage 组件。
<!-- <img :src="img.src" :alt="img.alt"> -->
<BaseImage :src="img.src" :alt="img.alt"/>