Theo Itzaris
Theo Itzaris

Reputation: 4681

How to make webpack bundle my assets/image/ although i call them from a url, into the component

Webpack is copying static png,jpg,svg files that are imported into each component file.
The file that hosts the image, it is fixed and the path is static.

The component file is like so: mycomponent.ts


import img from 'assets/img/aa.png

.... <img src={img} alt="" />

Below is a more complicated case.

  1. import an image from a url : import imgurl from ${url}
  2. use it into <img src={imgurl} />
  3. and webpack, still, move the images into static folder!! (this is my goal)

What i need webpack to do:.


  1. bundle the images from assets/img and move them into static/img, as if the images had been imported from assets/img, instead of url.
  2. so far webpack ignores the images that are imported from a url, possibly because it cant find them, during the build process
  3. but as i fake the js & css output with publicPath: config.output.publicPath = http://www...;,
    similarly can it be done for the images ?

snippet of bundling image, so far:


// so, this changes copy the imported, into react components, images, into 
// static/media
// but it copies ONLY the images that are imported from `assets/img`
// it ignores if i import an image from a url e.g. import img from ${url}

function addMedia(config, outputPath){
  const media = {
   test: /\.(woff(2)?|ttf|eot|svg|png)(\?v=\d+\.\d+\.\d+)?$/,
    use: [
    { 
      loader: 'file-loader',
      options: {
      name: '[name].[hash:8].[ext]',
      outputPath: 'static/media',
    }
  }
  ]
};
 config.module.rules.push( media );
}

So i wonder if there is a way to bundle/copy images from assets/img --> static/media, althougt into react file i import them from a url ?

Upvotes: 0

Views: 2931

Answers (1)

Mario Varchmin
Mario Varchmin

Reputation: 3782

You could use the copy-webpack-plugin to copy images from assets/img to static/media like so:

const CopyPlugin = require("copy-webpack-plugin");

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        { from: "assets/img", to: "static/media" }
      ],
      options: {
        concurrency: 100,
      },
    }),
  ],
};

Documentation of copy-webpack-plugin: https://webpack.js.org/plugins/copy-webpack-plugin/

Upvotes: 1

Related Questions