Example of converting webpack images to base64

Example of converting webpack images to base64

Download url-loader

 yarn add -D url-loader
module: {
  rules:
       {
        test: /\.(jpeg|jpg|png|svg|gif)$/,
        use: {
          loader: 'url-loader', // The default is es6 module options: { // Configure esModule: false, // Use common.js specification outputPath: 'images', // Output file directory name: 'images/[contenthash:4].[ext]',
            limit: 20*1024 // Convert to base64 if less than 20k
          }
        }
      }
  ]
}

You can see that the small picture has been converted to base64

insert image description here

Complete code

// webpack is based on node, so use module.exports
const path = require("path");

let HtmlWebpackPlugin = require("html-webpack-plugin"); // Generate html template const { CleanWebpackPlugin } = require("clean-webpack-plugin"); // Clear dist before each packaging

const MiniCssExtractPlugin = require("mini-css-extract-plugin"); // Merge CSS

// const OptimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin") // compress CSS

const CssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin"); // Latest compressed css

const TerserWebpackPlugin = require("terser-webpack-plugin"); // Compress js instead of uglify Because uglifyjs does not support es6 syntax, use terser-webpack-plugin instead of uglifyjs-webpack-plugin

const webpack = require("webpack"); // There is a ProvidePlugin inside, which can provide global variables const commonCssConfig = [ // Common CSS configuration MiniCssExtractPlugin.loader,
  "css-loader",
  {
    loader: "postcss-loader",
    options:
      //css compatibility configuration postcssOptions: {
        plugins: [[require("postcss-preset-env")()]],
      },
    },
  },
];
// Common babel transcoder configuration const babelConfig = {
  loader: 'babel-loader',
  options:
    presets: [
      "@babel/preset-env"
    ],
    "plugins": [
      ["@babel/plugin-proposal-decorators", { "legacy": true }],
      ["@babel/plugin-proposal-class-properties"]
    ]
  }
}
// Common plugin configuration const commonPlugin = [
  // html-webpack-plugin
  new HtmlWebpackPlugin({
    template: "./src/index.html", // Specify the template filename: "index.html", // Specify the output file name }),
  // new HtmlWebpackPlugin({ // Multiple templates// template: './src/index.html', // Specify template// filename: 'main.html', // Specify output file name// }),
  // clean-webpack-plugin
  new CleanWebpackPlugin(), // Use this plugin to delete the dist directory before generating the dist directory each time // mini-css-extract-plugin
  new MiniCssExtractPlugin({
    // Extract CSS and put it in the public folder filename: "css/[name].[hash:4].css", // Merge CSS public files }),
  // css-minimizer-webpack-plugin
  new CssMinimizerWebpackPlugin(), // New version of compressed css

  // terser-webpack-plugin
  new TerserWebpackPlugin({
    // Compress js
    test: /\.js(\?.*)?$/i, //Match files involved in compression parallel: true, //Use multiple processes to run concurrently terserOptions: {
      //Terser compression configuration output: { comments: false },
      compress: {
        // pure_funcs: ["console.log"], // remove console.log
      },
    },
    extractComments: true, // strip comments into separate files }),
  // Inject global variables and use them globally. No need to introduce new webpack.ProvidePlugin({
    $:"jquery"
  })
]

module.exports = {
  // Old version compressed css
  // optimization: {
  // minimizer: [new OptimizeCssAssetsWebpackPlugin]
  // },
  //Entry configuration entry: "./src/index.js",
  // Mode configuration mode: "production", // Specify the mode, the default is production mode, development mode is convenient for viewing code // Export configuration output: {
    path: path.resolve(__dirname, "dist"), // __dirname represents the root directory M:\47-webpack-study\01-webpack\dist
    filename: "js/[name].[hash:4].js", //Specify the output file name // [name] is a dynamic name, plus the hash value to avoid caching, the default is a 20-digit hash value /* 
     The role of hash:
     For example, when you package for the first time, the file will be cached by the browser. When you package for the second time, if the file name remains unchanged, the browser will not download the latest code, so the hash comes into play. The hash is also called the content hash value. As long as the content changes, the hash will change and will not be cached, keeping it updated at all times*/
  },
  // webpack-dev-server configures devServer: {
    host: "localhost", // host port: "9527", // port open: true, // Automatically open historyApiFallback: true, //If the page is not found, jump to index.html by default
    compress: true, //Enable gzip compression for all services hot: true, //Start hot update proxy: {
      // Proxy configuration "/api": {
        target: "http:localhost:5000",
        changeOrigin: true,
      },
    },
  },
  // Loader configuration module: {
    rules:
      {
        test: /\.html$/,
        use: 'html-withimg-loader', //Plugin for using images in HTML},
      {
        test: /\.js$/,
        use: babelConfig // babel transcoder configuration},
      {
        test: /\.css$/,
        use: [...commonCssConfig], // The css order is from right to left, from bottom to top},
      {
        test: /\.less$/,
        use: [...commonCssConfig,'less-loader'], // The order of less is from right to left and from bottom to top},
      {
        test: /\.scss$/,
        use: [...commonCssConfig,"sass-loader"], // The order of sass is from right to left and from bottom to top},
      // {
      // test: /\.(jpeg|jpg|png|svg|gif)$/,
      // use: {
      // loader: 'file-loader', // es6 module is used by default // options: { // Configuration // esModule: false, // Use common.js specification // outputPath: 'images', // Output file directory // name: 'images/[contenthash:4].[ext]',
      // }
      // }
      // }
      {
        test: /\.(jpeg|jpg|png|svg|gif)$/,
        use: {
          loader: 'url-loader', // The default is es6 module options: { // Configure esModule: false, // Use common.js specification outputPath: 'images', // Output file directory name: 'images/[contenthash:4].[ext]',
            limit: 20*1024 // Convert to base64 if less than 20k
          }
        }
      }
    ],
  },
  // Plug-in configuration plugins: [...commonPlugin],
  // Exclude third-party packages externals: {
    jquery: '$',
  }
};

Set the image not to be converted to base64 format in Webpack

During the development process, it is common to convert images to base64, such as uploading images. However, in some cases, you do not want to convert images to base64, because the images are not easy to distinguish after conversion to base64, and you cannot do other operations based on the image name. So how can you prohibit images from being converted to base64 in Webpack?

In fact, it is very simple. You only need to modify the Webpack configuration file webpack.base.conf.js, and change the limit of the image processing options in the rules under the module to 1, as shown in the figure below.

This is the end of this article about the implementation example of converting webpack images to base64. For more related content about converting webpack images to base64, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of webpack image import-enhanced file-loader: url-loader
  • Implementation and problems of introducing pictures in webpack
  • A brief discussion on webpack4 image processing summary
  • Solution to image path error after webpack configuration packaging
  • A brief discussion on the problem of obtaining the size of uploaded images using Webpack path compression
  • A brief discussion on the problems caused by the image path during webpack packaging
  • Solution to the error of directly accessing the page image path after webpack packaging

<<:  File upload via HTML5 on mobile

>>:  How to modify the previous command when an input error occurs in the MySQL command prompt

Recommend

Basic knowledge of MySQL database

Table of contents 1. Understanding Databases 1.1 ...

How to make CSS child elements highly consistent with parent elements

Absolute positioning method: (1) Set the parent e...

MySQL data types full analysis

Data Type: The basic rules that define what data ...

You really need to understand the use of CSS variables var()

When a web project gets bigger and bigger, its CS...

How to Understand and Identify File Types in Linux

Preface As we all know, everything in Linux is a ...

JavaScript realizes the drag effect of modal box

Here is a case of modal box dragging. The functio...

The image element img has extra blank space in IE6

When doing DIV+CSS layout of the page, it is very...

Basic knowledge: What does http mean before a website address?

What is HTTP? When we want to browse a website, w...

Some thoughts and experience sharing on web page (website) design and production

First, before posting! Thanks again to I Want to S...

After reading the introduction of CSS box model, you will not be confused

The property names often heard in web design: con...

A brief discussion on the principle of shallow entry and deep exit of MySQL

Table of contents 1. Overview of the page 2. Infi...

How to build a tomcat image based on Dockerfile

Dockerfile is a file used to build a docker image...

Implementation code for partial refresh of HTML page

Event response refresh: refresh only when request...

How to modify the initial password of MySQL on MAC

Problem description: I bought a Mac and installed...

How to limit the input box to only input pure numbers in HTML

Limit input box to only pure numbers 1、onkeyup = ...