webpack packaging images

 We can use webpack to package images. The specific steps of packaging are as follows:

1. We need file-loader when packaging images. Install fly-loader.

npm install --save-dev file-loader

2. Configure webpack.fig.js

  module:{
  rules:[
    {
      test:/\.(png|svg|jpg|gif)$/,
      use:["file-loader?limit=8192&name=dist/[hash].[ext]"]
    }
    ]
  }
};

Note: limitiet means: when the image size is less than the limit, use base64 transcoding. When the limit is greater than the limit, it will be packaged normally.

        name: Change the loading path of the image through the name attribute. (The image will import the img element in index.html. This path is the import path of the image

        hash: After the image is processed, an image will be generated in the output folder. At this time, the name of the image is hash. ext represents the format of the image.

3. The structure of the project is as follows

webpack_demo
  --node_modules               
  --src
    --index.js
    --icon.jpg
    --style.css
  --webpack.config.js
  --package.json
  --index.js

4.index.js is as follows:

import './style.css';
 import Icon from "./icon.jpg"

  function component() {
    var element = document.createElement('div');

    element.innerHTML ="hello webpack";
    element.classList.add('hello');

    var myIcon = new Image();
  	myIcon.src = Icon;
    console.log(myIcon);

    element.appendChild(myIcon);

    return element;
  }
  document.body.appendChild(component());
When you  import MyImage from './my-image.png' , the image will be processed and added to the dist  directory, and MyImage  The variable will contain the final url of this image after processing.

5.style.css file:

.hello {
  color: red;
  background: url('./icon.jpg');
}

5. Pack:

webpack --mode development
At this point, you will see that the image name under dist has been changed. Open index.htm. You will see the page displayed. There is an img tag in the body (pay attention to the src attribute of the image, which is the same as the path configured in step 2). There are also style tags in the head.



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325887777&siteId=291194637