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

Vue.js中如何正确加载动态图片?静态加载正常但require加载报错

Vue动态图片加载报错:Module not found

刚学Vue.js,静态加载图片正常,但用require()动态加载时出现「Module not found: Error: Can't resolve」错误。

可正常运行的静态图片加载代码

<template>
    <img :src="'../img/' + message.filename" alt="img"/>
</template>

无法运行的动态图片加载尝试

<template>
    <img :src="require('../img/' + message.filename)" alt="img"/>
</template>

也曾尝试以下路径写法:

  • require('@/img/' + message.filename)
  • require('@/assets/img/' + message.filename)

项目文件夹结构

/src
   /assets
      /img
         image_1.jpg
         image_2.jpg
   /resources
      /static
         /components
            App.vue
      main.js

Webpack.config.js 配置

const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin');

module.exports = {
  mode: 'development',
  devtool: 'source-map',
  entry: path.join(__dirname, 'src', 'main', 'resources', 'static', 'js', 'main.js'),
  devServer: {
    contentBase: './static',
    compress: true,
    port: 8000,
    allowedHosts: [
      'localhost:8080'
    ],
    stats: 'errors-only',
    clientLogLevel: 'error',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /\.css$/,
        use: [
            'vue-style-loader',
            'css-loader'
             ]
      }
    ]
  },
  plugins: [
    new VueLoaderPlugin()
  ],
  resolve: {
      modules: [
          path.join(__dirname, 'src', 'main', 'resources', 'static', 'js'),
          path.join(__dirname, 'node_modules'),
      ],
      extensions: ['.js']
  }
}

问题原因与解决办法

1. Webpack缺少图片资源处理规则

当前Webpack配置未添加图片文件解析的loader,导致require()加载图片时无法识别资源类型。需在module.rules中新增规则:

{
  test: /\.(png|jpe?g|gif|svg)$/i,
  use: [
    {
      loader: 'file-loader',
      options: {
        name: '[name].[ext]',
        outputPath: 'img/' // 打包后图片输出目录
      }
    }
  ]
}

安装依赖:

npm install file-loader --save-dev

2. 动态路径的Webpack编译限制

Webpack编译时需要明确知道打包资源,动态拼接的路径(如'../img/' + message.filename)因包含运行时变量,无法被预解析。可通过两种方式处理:

  • 手动映射图片路径:
<template>
  <img :src="imageMap[message.filename]" alt="img"/>
</template>

<script>
import image1 from '@/assets/img/image_1.jpg'
import image2 from '@/assets/img/image_2.jpg'

export default {
  data() {
    return {
      imageMap: {
        'image_1.jpg': image1,
        'image_2.jpg': image2
      }
    }
  }
}
</script>
  • 用require.context批量导入:
<template>
  <img :src="getImage(message.filename)" alt="img"/>
</template>

<script>
const images = require.context('@/assets/img', false, /\.(jpg|jpeg|png)$/)

export default {
  methods: {
    getImage(filename) {
      try {
        return images('./' + filename)
      } catch (e) {
        return '' // 图片不存在时返回空或默认图
      }
    }
  }
}
</script>

3. 配置@别名指向src目录

当前Webpack未配置@别名,导致@/assets/img路径无法识别。在resolve中添加别名:

resolve: {
  alias: {
    '@': path.join(__dirname, 'src')
  },
  // 原有modules、extensions配置...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 07:55:47