A, use,file-loaderLoading pictures

  • 1. Installation package

    npm install file-loader -D
    Copy the code
  • 2. Use in JS

    let src = require('./images/default.jpeg');
    let img = new Image();
    img.src = src;
    document.body.appendChild(img);
    Copy the code
  • 3. Configure rules

    {
    	test: /\.(png|jpg|gif|svg|bmp|jpeg)$/.use: 'file-loader',},Copy the code

Second, incssWrite a background image in the file

  • 1. Style files

    #box {
      width: 100px;
      height: 100px;
      border: 2px solid # 333;
      background: url('. /.. /images/default.jpeg');
      background-size: cover;
    }
    Copy the code
  • 2. This configuration is required in webpack.config.js

    . {test: /\.(png|jpg|gif|svg|bmp|jpeg|eot|woff|woff2|ttf)$/.use: [{loader: 'url-loader'.options: {
    				limit: 5 * 1024.// Specify the size of the image
    				outputPath: 'images'.// Specify the output directory for copied files
    				publicPath: '.. /.. /images/'.// Jump to the image path from the webpack root
    				// name: '[name].[hash:8].[ext]',}}]},...Copy the code

If you want to use image tags directly on the page

  • 1. Installation package

    npm install html-withimg-loader -D
    Copy the code
  • 2. Configure rules

    {
    	test: /\.(html|htm)$/.use: [{loader: 'html-withimg-loader',}}]Copy the code
  • 3, use,

    <img src="./images/default.jpeg" width="200" height="200"/>
    Copy the code

Four, the use ofbase64Processing images

  • 1. File-loader resolves the image address, copies the image from the source location to the destination location, and modifies the source reference

  • 2. Url-loader can directly convert small files into Base64 strings and nest them in pages

    {
    	test: /\.(png|jpg|gif|svg|bmp|jpeg|eot|woff|woff2|ttf)$/.use: [{loader: 'url-loader'.options: {
    				limit: 5 * 1024.// Specify the size of the image
    				outputPath: 'images/'.// Specify the output directory for copied files}}},Copy the code