In the previous lessons we saw how to use
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> directly in html.
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
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
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 attribute values for the two
img tags above (line # 15 and 20) now use the relative paths for the image files.
$ npm install --save-dev copy-webpack-plugin
4. Import the plugin in webpack.config and add it to plugins array as below:
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 ]