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

mysql 5.7.11 winx64.zip installation and configuration method graphic tutorial

Install and configure the MySql database system. ...

Linux platform mysql enable remote login

During the development process, I often encounter...

Detailed explanation of vue.js dynamic components

:is dynamic component Use v-bind:is="compone...

How to remove the dividing line of a web page table

<br />How to remove the dividing lines of a ...

Tutorial on configuring and using i3 window manager in Linux

In this article, I will show you how to install a...

Detailed explanation of the application of CSS Sprite

CSS Sprite, also known as CSS Sprite, is an image...

Detailed tutorial on downloading mysql on Windows 10

MySQL versions are divided into Enterprise Editio...

20 CSS coding tips to make you more efficient (sorted)

In this article, we would like to share with you ...

Docker uses Supervisor to manage process operations

A Docker container starts a single process when i...

CentOS 8.0.1905 installs ZABBIX 4.4 version (verified)

Zabbix Server Environment Platform Version: ZABBI...

Introduction to Enterprise Production MySQL Optimization

Compared with other large databases such as Oracl...

Vue backend management system implementation of paging function example

This article mainly introduces the implementation...

How to enter and exit the Docker container

1 Start the Docker service First you need to know...

Tutorial on installing mysql5.7.36 database in Linux environment

Download address: https://dev.mysql.com/downloads...