Loading images

Now, let's try loading images and icons using the file loader, which can be easily incorporated into our system.

To do this, perform the following steps:

  1. Using the command line, install file-loader, as follows:
npm install --save-dev file-loader
  1. Now, using the usual  webpack.config.js Webpack configuration file, make the following amendments to it:
  const path = require('path');
module.exports = { entry: './src/index.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') }, module: { rules: [ { test: /.css$/, use: [ 'style-loader', 'css-loader' ] }, { test: /.(png|svg|jpg|gif)$/,
use: [
'file-loader'
] } ] } };

Now, because of the code in the previous block, when you import an image, that image will be processed to the output directory, and the variable associated with that image will contain the final URL of that image after processing. When using the css-loader, a similar process will occur for the URL of the image file within your CSS file. The loader will recognize that this is a local file and replace the local path with the final path to the image in your output directory. The html-loader handles <img src="./my-image.png" /> in the same manner.

  1. Next, to start adding an image, you need to navigate to the project file structure, which looks like this:
  webpack5-demo
  |- package.json
  |- webpack.config.js
  |- /dist
    |- bundle.js
    |- index.html
  |- /src
    |- icon.png
    |- style.css
    |- index.js
  |- /node_modules

This structure seems very similar to the immediately previous project directly used for the Loading CSS files tutorial for the most part, except for the addition of the icon.png image file.

  1. Then, navigate to the JavaScript frontend file, src/index.js. The following code block shows the content:
import _ from 'lodash'; import './style.css';  
import Icon from './icon.png';
function component() {
const element = document.createElement('div');
// Lodash, now imported by this script
element.innerHTML = _.join(['Hello', 'Webpack'], ' ');
element.classList.add('hello');
// Add the image to our existing div.

const myIcon = new Image();

myIcon.src = Icon;

element.appendChild(myIcon);

return element;
}
document.body.appendChild(component());

It can be seen from this preceding block that the import of lodash will allow the HTML of your page to be appended with the Hello Webpack text. Beyond that, this code simply sets up our web page with our image, using some crafty JavaScript. It first creates a variable called Icon and gives it the value of the image file's URL. Later in the code, it then assigns this to the source of an element called myIcon.

  1. From here, we want to set some very basic styles to handle our image with the style sheet. In the src/style.css file, append the following code:
  .hello {
    color: red;
    background: url('./icon.png');
  }

It will, of course, show your image icon as the background for div we assigned code to in the HTML, with the text turned red wherever the .hello class is applied.

  1. Run a new build and open up the index.html file, as follows:
npm run build

...
Asset                                 Size          Chunks         Chunk Names
da4574bb234ddc4bb47cbe1ca4b20303.png  3.01 MiB          [emitted]  [big]
bundle.js                             76.7 KiB       0  [emitted]         main
Entrypoint main = bundle.js
...

This will create the effect of the icon repeating as a background image. There will also be an img element beside the Hello Webpack text.

Often, this command can go wrong, even for experienced developers. For example, the image might not load at all, be too large, or will not be bundled correctly. This can be caused by a combination of factors, including the use of the loader in an unusual way. Webpack may also experience code skipping when using long filenames.

If this is the case, simply repeat the steps, as follows:

  1. Install file-loader using the command line.
  2. Alter the webpack.config.js file, as described in the preceding example.
  3. Check that the project file structure and index file are formatted correctly to load the image file.
  4. Check that the CSS is also formatted the way you want it to be.
  5. Then, run the build using npm and the command line.
  6. Check that the index file is loading the image correctly.

If the element is inspected, the actual filename can be seen to have changed to something similar to da4574bb234ddc4bb47cbe1ca4b20303.png. This means that Webpack found our file in the source folder and processed it.

That gives you a solid framework for managing images. In the next subsection, we will discuss the management of fonts as Webpack assets.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.94.152