为什么我无法使用 webpack-5 从 json 文件加载图像?

问题描述 投票:0回答:2

当我在 html 中使用 IMG 标签时,它工作得很好。但是,当我尝试在 Javascript 中生成一些带有图像 URL(来自 JSON 文件)的 HTML 并将其插入时,图像会被插入,但不会带有哈希值,而且所需的图像也不会被插入生成在图像文件夹中。 Webpack 只是跳过它。我很努力,但找不到方法。请帮我!我很沮丧。

这是我的 json 数据:

{
  "persons": [
    {
      "id": 1,
      "image": "./images/avatars/image-alex.png"
    },
    {
      "id": 1,
      "image": "./images/avatars/image-tom.png"
    }
  ]
}

这是我的 Webpack 配置:

const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
  entry: "./src/js/index.js",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "bundle.js",
  },
  mode: "development",
  devServer: {
    port: 2222,
    hot: false,
    open: true,
  },
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
      },
      {
        test: /\.html$/,
        loader: "html-loader",
      },
      {
        test: /\.(png|jpe?g|gif|svg)$/i,
        type: "asset/resource",
        generator: {
          filename: "images/[name].[hash].[ext]",
        },
      },
      {
        test: /\.json$/i,
        type: "asset/resource",
        generator: {
          filename: "data/[name].[hash].[ext]",
        },
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css",
    }),

    new HtmlWebpackPlugin({
      template: "./src/index.html",
    }),
    new CleanWebpackPlugin(),
  ],
};

这是我的JavaScript:

import rawJson from "../json/data.json";
const containerEl = document.querySelector(".all-persons-container");

const dataJson = async () => {
  const response = await fetch(rawJson);
  const data = await response.json();
  return data;
};

let allPersons = await dataJson().then((data) => {
  return data.persons;
});

const img = allPersons[0].image;
console.log(img);

const insert = async () => {
  const markup = `
      <img
        src="${img}"
      />
    `;

  containerEl.insertAdjacentHTML("afterbegin", markup);
};

insert();

我还附上了我的项目树:Preject tree

javascript json debugging webpack webpack-5
2个回答
0
投票

源图像文件必须导入或在JavaScript中需要:

import img from "./images/avatars/image-alex.png";
// OR
const img = require("./images/avatars/image-alex.png");

console.log(img); // => output image file

Webpack 解析 JS 代码并在“服务器端”提取所需的图像,变量

img
将包含已处理的图像输出文件名。

但是在运行时这是不可能的,浏览器不知道你的源图像在哪里。


0
投票

我也有同样的错误。 基于 biodiscus 答案,我的解决方案(由于时间原因)将 .json 文件转换为 .js 文件并添加所需的硬编码 URL

    //original Json file
    {
      "persons": [
        {
          "id": 1,
          "image": "./images/avatars/image-alex.png"
        },
        {
          "id": 1,
          "image": "./images/avatars/image-tom.png"
        }
      ]
    }

    //js converted file
    export default {
      "persons": [
        {
          "id": 1,
          "image": require("./images/avatars/image-alex.png")
        },
        {
          "id": 1,
          "image": require("./images/avatars/image-tom.png")
        }
      ]
    }

您可以在 vscode 中使用正则表达式将所有 url 字符串替换为 require: Example image Replace regex image

© www.soinside.com 2019 - 2024. All rights reserved.