首页 > 解决方案 > Next.js 无法在运行时提供动态图像

问题描述

因此,我将 Next.js API 用于我的项目后端,并将 Mongodb 用于数据库。我必须提供用户在运行时上传的图像。由于这些文件在构建期间尚不可用,因此它们不会被识别为可以存储在public目录中的静态文件。

我已经尝试过next-imagesnext.config.js ,并在我的代码中添加了一些配置: <img src={require(../../../images/${picture.src} )} alt={picture.legend} />

但我仍然有这个错误:模块解析失败

我也尝试过使用文件加载器,但仍然没有运气。

我错过了什么?

感谢您的回复!

标签: reactjsimagenext.js

解决方案


过去在加载图像和/或字体时遇到这些问题时,此配置对我有用:

  1. npm install url-loader --save-dev

  2. next.config.js

module.exports = {
  webpack: function (config) {
    config.module.rules.push({
      test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
      use: {
        loader: 'url-loader',
        options: {
          limit: 100000,
          name: '[name].[ext]',
        },
      },
    });
    return config;
  },
}

推荐阅读