Vue3项目使用template属性渲染时出现require is not a function错误
Vue3 CLI项目图片渲染异常问题解析
问题核心原因
两种写法的差异本质在于模板是否被Webpack预处理:
- Home.vue是标准单文件组件(SFC),独立
<template>标签的内容会被vue-loader和Webpack提前解析处理。模板里的require('@/assets/xxx.svg')会被Webpack替换为打包后的图片URL,运行时无需执行require函数,因此能正常渲染。 - InitializationModal.vue的模板写在组件的
template字符串属性中,这段模板是在浏览器运行时才被Vue编译的。此时模板里的require会被当作普通JS代码执行,但浏览器环境(尤其是Vue3+Webpack5默认使用ES模块的场景下)不存在require函数,所以触发TypeError: require is not a function错误。
解决方案
方案1:改为标准单文件组件写法
将模板从template属性移出,使用独立<template>标签,和Home.vue保持一致:
<template> <div class="hardwareConfiguration flex flex-column"> <h4>Hardware Configuration</h4> <v-select :options="Datacenters" @input="validateDatacenter" label="title"> <template slot="Datacenter" slot-scope="Datacenter"> <img :src="require('@/assets/some_image.svg')" style="height: 20%; width: 20%" /> {{ Datacenter.DatacenterName }} </template> </v-select> </div> </template> <script> export default { name: "hardwareConfiguration", // 组件逻辑写在这里 }; </script>
方案2:提前在script中引入图片资源
如果必须使用字符串模板,提前在script中通过import或require引入图片,将资源URL存入data后再在模板中引用:
<script> // 提前引入图片,Webpack会处理并返回打包后的URL import someImage from '@/assets/some_image.svg' export default { name: "hardwareConfiguration", data() { return { someImageSrc: someImage } }, template: ` <div class="hardwareConfiguration flex flex-column"> <h4>Hardware Configuration</h4> <v-select :options="Datacenters" @input="validateDatacenter" label="title"> <template slot="Datacenter" slot-scope="Datacenter"> <img :src="someImageSrc" style="height: 20%; width: 20%" /> {{ Datacenter.DatacenterName }} </template> </v-select> </div> `, }; </script>
额外说明
Vue3官方推荐使用单文件组件(SFC)写法,这种方式不仅能让Webpack更好地处理静态资源,还能提升代码的可读性与可维护性。若特殊场景下需要使用字符串模板,所有静态资源的引入都应提前在script中完成,避免在模板字符串内直接调用require或import。
内容的提问来源于stack exchange,提问作者CraZyCoDer
相关产品推荐
相关产品推荐

