You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt动态图片加载报错:Require is not defined

Nuxt动态图片加载报错「Require is not defined」解决办法

你遇到的问题是因为Nuxt 3默认使用Vite作为构建工具,而Vite不支持CommonJS的require语法,旧文档里的写法是给Nuxt 2(基于Webpack)设计的,所以会触发报错。

给你两种可行的解决方案:

方案一:批量预加载图片(适合多张动态图片场景)

用Vite的import.meta.glob提前加载指定目录下的所有图片,之后动态匹配路径:

<template>
  <img :src="getImageUrl(image)" />
</template>

<script setup>
// 预加载assets/img目录下所有jpg格式的图片
const images = import.meta.glob('~/assets/img/*.jpg', { eager: true, import: 'default' })

// 根据图片名称返回对应路径
const getImageUrl = (imageName) => {
  return images[`/assets/img/${imageName}.jpg`] || ''
}
</script>

方案二:单张图片动态构建路径(适合少量动态图片场景)

用new URL结合import.meta.url动态生成图片地址:

<template>
  <img :src="getImageUrl(image)" />
</template>

<script setup>
const getImageUrl = (imageName) => {
  return new URL(`../assets/img/${imageName}.jpg`, import.meta.url).href
}
</script>

如果你的项目是Nuxt 2,那可能是Webpack配置有误,需确保assets目录被正确解析,但目前大部分新项目都是Nuxt 3,优先用上面的Vite兼容写法即可。

内容的提问来源于stack exchange,提问作者YMH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 06:15:44