Copy all images/files to a folder using copy-webpack-plugin

Bharat Tiwari
A beginner’s guide to Webpack 2
3 min readMay 24, 2017

In the previous lessons we saw how to use url-loader andfile-loader that allow webpack to bundle/pack images used in our web application. For webpack to know what images our application uses, we have to let webpack know of those images as our dependencies by importing / requiring the image files in somewhere in our javascript dependencies like

import homeIcon from '../images/home.png';

With webpack allowing us to import images as modules, in frameworks, like angular or react, that allow using HTML templates, two-way binding of variables or JSX, its easy to specify src for an <img> tag to the image imported in javascript as we saw in the previous lesson. However sometimes if you have too many images on the page, or if you are not using html templates or js-to-html bindings, then importing images in javasscript may not make much sense. Rather you may specify the src path for <img> directly in html.

With no import/require statements for our image resources in javascript, webpack would not process the images as part of bundling as it won’t see those as dependencies.

In such cases, we can configure webpack to copy all our image resources to the dist folder using ‘CopyWebpackPlugin’. With images copied to the distfolder, our relative paths in src of <img> tags in html should work.

Lets try this approach, specifying our src of <img> tags directly in html instead of setting those from javascript.

1. In ./src/scripts/app.js, remove the two import statements for home.png and nature.jpg , also remove the code that sets the src for the two <img> tags:

Above, we commented the importing of our image files in app.js( line # 6–13).

2. In ./src/index.html, specify the src for the two <img> tags as relative paths to the two images:

./src/index.html

Note the src attribute values for the two img tags above (line # 15 and 20) now use the relative paths for the image files.

3. Install CopyWebpackPlugin

$ npm install --save-dev copy-webpack-plugin

4. Import the plugin in webpack.config and add it to plugins array as below:

./webpack/webpack.config.js

Above, in webpack.config.js, we imported copy-webpack-plugin (line # 3) amd then added and configured the plugin in the plugins array (line # 12–14).

5. Now when you run npm start again, the CopyWebpackPlugin will copy all the files in src/images to ‘images‘ folder inside our output ‘dist’ folder. When you open/refresh the index.html in the browser, the images should be seen, now being served from the ‘images’ folder.

That concludes our ‘handling images in webpack’ topic. Next we will see how to use ‘public-path’ setting in webpack.config.js to publish our script bundles and images in some remote path.

[ Prev: File-loader ] [Next: Public-path ]

--

--