How to bundle dynamic image path using webpack

Viewed 68

webpack works well with import syntax.

import image1 from '../public/assets/image1.png'

image1.png is bundled successfully.


But I want to pass the image src using props like below.


const paths = ['../public/assets/image1.png','../public/assets/image2.png']

const Parent = () => {
  return (
    <div>
      <Child srcPath={path[0]} />
    </div>
  );
};

const Child = ({srcPath}) => {
  return (
    <img src={srcPath} />
  )
}

webpack not bundle png files.

How do I let webpack bundle without import syntax?

My webpack version is 5.24.3 and this is my webpack.config.js

// webpack.config.js
module.exports = {
  mode: "development",
  entry: { index: path.resolve(__dirname, "src", "app.tsx") },
  output: {
    path: path.resolve(__dirname, "build"),
    assetModuleFilename: "images/[hash][ext][query]",
  },
  resolve: { extensions: [".ts", ".tsx", ".js"] },
  module: {
    rules: [
      { test: /\.tsx?$/, loader: "ts-loader" },
      { test: /\.(png|svg|jpg|jpeg|gif)$/i, type: "asset/resource" },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "public/index.html",
    }),
  ],
  devServer: {
    contentBase: path.join(__dirname, "build"),
    host: "localhost",
    port: port,
    historyApiFallback: true,
    hot: true,
  },
};
0 Answers
Related