2022 年最流行的 Webpack 插件,你用上了吗

在这里插入图片描述

如果我们有合适的工具,开发就会变得更容易。在这篇文章中,我将讨论一些流行的webpack插件。

Webpack Dashboard

以上输出很难阅读和理解。此外,信息没有很好地格式化和呈现。

这里webpack仪表盘的图片有一个更好的视觉输出。通过在cmd中键入命令来安装它。

npm install --save-dev webpack-dashboard
# or
$ yarn add --dev webpack-dashboard

注:webpack-dashboard@^3.0.0需要node8+或以上。以前的版本只支持node6。

现在,我们需要在·webpack.config.js·中导入这个插件,并添加到plugins数组中。

//webpack.config.js

const path = require('path');
const webpackDashboard = require('webpack-dashboard/plugin');
module.exports = {
   entry: './src/index.js',
   output: {
      path: path.join(__dirname, '/dist'),
      filename: 'bundle.js'
   },
   devServer: {
      port: 8080
   },
   module: {
      rules: [
         {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
         },
         {
            test: /\.css$/,
            use: [ 'style-loader', 'css-loader' ]
        }
      ]
   },
   plugins:[
       new webpackDashboard() // add
   ]
}

还需要在package.json中修改你的脚本。只需要在每个脚本之前附加webpack-dashboard。

"scripts": {
    "start": "webpack-dashboard -- webpack serve --mode development --open --hot",
    "build": "webpack-dashboard -- webpack --mode production"
  }

运行应用程序,您将看到一个非常棒的构建过程输出。😍

Terser Webpack Plugin

terser webpack插件用于压缩你的JavaScript包的大小以供生产使用。这个插件还支持ES6+JavaScript语法。

注意:Terser webpack插件默认是webpack 5自带的

使用下面的命令安装这个插件:

npm install --save-dev terser-webpack-plugin

然后导入并添加这个插件到你的webpack.config.js中:

//webpack.config.js

const path = require('path');
const webpackDashboard = require('webpack-dashboard/plugin');
const TerserPlugin = require("terser-webpack-plugin");

module.exports = {
   entry: './src/index.js',
   output: {
      path: path.join(__dirname, '/dist'),
      filename: 'bundle.js'
   },
   optimization: {
      minimize: true,
      minimizer: [new TerserPlugin()],
    },
   devServer: {
      port: 8080
   },
   module: {
      rules: [
         {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
         },
         {
            test: /\.css$/,
            use: [ 'style-loader', 'css-loader' ]
        }
      ]
   },
   plugins:[
       new webpackDashboard()
   ]
}

Optimize CSS Assets Webpack Plugin

这个插件将搜索你项目中的所有CSS文件,并优化/压缩CSS

npm install --save-dev optimize-css-assets-webpack-plugin mini-css-extract-plugin css-loader

webpack.config.js.:

//webpack.config.js

const path = require('path');
const TerserPlugin = require("terser-webpack-plugin");
const webpackDashboard = require('webpack-dashboard/plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
   entry: './src/index.js',
   output: {
      path: path.join(__dirname, '/dist'),
      filename: 'bundle.js'
   },
   optimization: {
      minimize: true,
      minimizer: [new TerserPlugin(), new MiniCssExtractPlugin()],
    },
   devServer: {
      port: 8080
   },
   module: {
      rules: [
         {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
         },
         {
            test: /\.css$/i,
            use: [MiniCssExtractPlugin.loader, 'css-loader'],
         }, 
      ]
   },
   plugins:[
       new webpackDashboard(),
       new MiniCssExtractPlugin(),
       new OptimizeCssAssetsPlugin({
         assetNameRegExp: /\.optimize\.css$/g,
         cssProcessor: require('cssnano'),
         cssProcessorPluginOptions: {
           preset: ['default', { discardComments: { removeAll: true } }],
         },
         canPrint: true
       })
   ]
}

HTML Webpack Plugin

HTML webpack插件,用于生成HTML文件,用JavaScript代码注入脚本标签。这个插件用于开发和生产构建。

使用以下方法安装此插件:

npm install --save-dev html-webpack-plugin

webpack.config.js:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const TerserPlugin = require("terser-webpack-plugin");
const webpackDashboard = require('webpack-dashboard/plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');


module.exports = {
   entry: './src/index.js',
   output: {
      path: path.join(__dirname, '/dist'),
      filename: 'bundle.js'
   },
   optimization: {
      minimize: true,
      minimizer: [new TerserPlugin(), new MiniCssExtractPlugin()],
    },
   devServer: {
      port: 8080
   },
   module: {
      rules: [
         {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
         },
       {
         test: /\.css$/i,
         use: [MiniCssExtractPlugin.loader, 'css-loader'],
     }, 
      ]
   },
   plugins:[
       new HtmlWebpackPlugin(
         Object.assign(
           {},
           {
             inject: true,
             template: path.join(__dirname,'/src/index.html')
           },

           // Only for production
           process.env.NODE_ENV === "production" ? {
             minify: {
               removeComments: true,
               collapseWhitespace: true,
               removeRedundantAttributes: true,
               useShortDoctype: true,
               removeEmptyAttributes: true,
               removeStyleLinkTypeAttributes: true,
               keepClosingSlash: true,
               minifyJS: true,
               minifyCSS: true,
               minifyURLs: true
             }
           } : undefined
         )
       ),
       new webpackDashboard(),
       new MiniCssExtractPlugin(),
       new OptimizeCssAssetsPlugin({
         assetNameRegExp: /\.optimize\.css$/g,
         cssProcessor: require('cssnano'),
         cssProcessorPluginOptions: {
           preset: ['default', { discardComments: { removeAll: true } }],
         },
         canPrint: true
       })
   ]
}

Clean Webpack Plugin

Clean webpack插件用于清理/删除你的构建文件夹。它还将在每次成功重建后删除所有未使用的webpack assets。

这个插件将帮助减少包的大小,删除不需要的文件和assets文件

使用以下方法安装此插件:

npm install --save-dev clean-webpack-plugin

webpack.config.js:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const webpackDashboard = require("webpack-dashboard/plugin");
const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
  entry: "./src/index.js",
  output: {
    path: path.join(__dirname, "/dist"),
    filename: "bundle.js",
  },
  optimization: {
    minimize: true,
    minimizer: [new TerserPlugin(), new MiniCssExtractPlugin()],
  },
  devServer: {
    port: 8080,
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: "babel-loader",
      },
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin(
      Object.assign(
        {},
        {
          inject: true,
          template: path.join(__dirname, "/src/index.html"),
        },

        // Only for production
        process.env.NODE_ENV === "production"
          ? {
              minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeRedundantAttributes: true,
                useShortDoctype: true,
                removeEmptyAttributes: true,
                removeStyleLinkTypeAttributes: true,
                keepClosingSlash: true,
                minifyJS: true,
                minifyCSS: true,
                minifyURLs: true,
              },
            }
          : undefined
      )
    ),
    new webpackDashboard(),
    new MiniCssExtractPlugin(),
    new OptimizeCssAssetsPlugin({
      assetNameRegExp: /\.optimize\.css$/g,
      cssProcessor: require("cssnano"),
      cssProcessorPluginOptions: {
        preset: ["default", { discardComments: { removeAll: true } }],
      },
      canPrint: true,
    }),
    new CleanWebpackPlugin({
      // Use !negative patterns to exclude files
      // default: []
      cleanAfterEveryBuildPatterns: ["static*.*", "!static1.js"],

      // Write Logs to Console
      // (Always enabled when dry is true)
      // default: false
      verbose: true,
    }),
  ],
};

你可以看到,在运行npm run build之后,dist文件夹下的所有文件都会被删除,之后只会发出必需的文件,temp.js也会被删除,因为它在任何文件中都没有引用。

感谢阅读这篇博客文章。如果你在使用webpack配置这些插件时遇到任何问题,请随时在评论框中发表评论。

如果你觉得这篇文章有用,请与你的朋友和同事分享!❤️

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程轨迹_

期望和你分享一杯咖啡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值