SoFunction
Updated on 2025-04-14

Detailed explanation of the functions of some common configurations of front-end webpack

1. Loader

Loader is used to convert the source code of the module. It can convert non-JavaScript files (such as CSS, pictures, fonts, etc.) into modules that webpack can handle.

Common Loaders and their functions

Loader effect
babel-loader Convert ES6+ code to ES5, compatible with older browsers.
css-loader Parsing CSS files and processing@importandurl()etc.
style-loader Insert CSS into the DOM and pass<style>The label takes effect.
sass-loader Compile the SCSS/SASS file into CSS.
file-loader Process files (such as pictures, fonts), output them to the build directory and return to the file path.
url-loader Similar tofile-loader, but can convert small files to Base64 URLs, reducing HTTP requests.
ts-loader Compile TypeScript into JavaScript.
 = {
  module: {
    rules: [
      {
        test: /\.js$/, // Match .js files        exclude: /node_modules/, // Exclude node_modules directory        use: 'babel-loader', // Use babel-loader      },
      {
        test: /\.css$/, // Match .css files        use: ['style-loader', 'css-loader'], //Execute from right to left      },
      {
        test: /\.(png|jpe?g|gif|svg)$/, // Match the image file        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8192, // Convert files less than 8KB to Base64 URL              name: 'images/[name].[hash:8].[ext]', // Output path and file name            },
          },
        ],
      },
    ],
  },
};

2. Plugin

Plugin is used to extend the functionality of webpack and allows you to perform custom actions at all stages of the packaging process. Unlike Loader, Plugin has a wider range of functions, such as optimizing resources, managing environment variables, injecting global variables, etc.

Commonly used Plugins and their functions

Plugin effect
HtmlWebpackPlugin Automatically generate HTML files and automatically inject packaged resources (such as JS, CSS).
MiniCssExtractPlugin Extract CSS as a separate file instead of embedding it into JS.
CleanWebpackPlugin Clean the output directory before each build to avoid remnants of old files.
DefinePlugin Define global constants, which are usually used to distinguish between development and production environments.
CopyWebpackPlugin Copy static files (such as pictures, fonts) to the output directory.
HotModuleReplacementPlugin Enable module hot replacement (HMR) to update the module without refreshing the page.
OptimizeCSSAssetsPlugin Compress and optimize CSS files.
TerserWebpackPlugin Compress and optimize JavaScript files.
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const webpack = require('webpack');

 = {
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/', // Specify HTML template      filename: '', // The output HTML file name    }),
    new MiniCssExtractPlugin({
      filename: 'css/[name].[contenthash:8].css', // Extract CSS to a separate file    }),
    new CleanWebpackPlugin(), // Clean the output directory    new ({
      '.NODE_ENV': ('production'), // Define environment variables    }),
  ],
};

3. Other common configurations

1) entry

Specifies the packaged entry file.

 = {
  entry: './src/', // Single entrance  // Multiple entrances  entry: {
    app: './src/',
    admin: './src/',
  },
};

2) output

Specifies the packaged file output location and file name.

 = {
  output: {
    path: (__dirname, 'dist'), // Output directory    filename: 'js/[name].[contenthash:8].js', // Output file name    publicPath: '/', // Public path (for CDN)  },
};

3) mode

Set packaging mode, optionaldevelopmentproductionornone

 = {
  mode: 'production', // Production mode (code compression is enabled by default)};

4) devServer

Configure the development server and support hot updates, proxying and other functions.

 = {
  devServer: {
    contentBase: './dist', // Service Content Directory    hot: true, // Enable hot updates    port: 8080, // Port number    proxy: {
      '/api': 'http://localhost:3000', // proxy API request    },
  },
};

5) optimization

Configure code segmentation and compression optimization.

 = {
  optimization: {
    splitChunks: {
      chunks: 'all', // Code segmentation    },
    minimizer: [
      new TerserWebpackPlugin(), // Compress JS      new OptimizeCSSAssetsPlugin(), // Compress CSS    ],
  },
};

4. Summary

  • Loader: Used to process specific types of files (such as CSS, pictures, fonts, etc.) and convert them into modules that webpack can handle.

  • Plugin: Used to extend webpack functions, such as generating HTML files, extracting CSS, compressing code, etc.

  • Common configurationsentryoutputmodedevServeroptimizationwait.

This is the end of this article about the role of some common configurations of front-end webpack. For more related contents of common configurations of front-end webpack, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!