前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >2022年开发者都在用的 Webpack 插件,你用上了吗

2022年开发者都在用的 Webpack 插件,你用上了吗

作者头像
前端修罗场
发布2022-07-29 08:13:44
5070
发布2022-07-29 08:13:44
举报
文章被收录于专栏:Web 技术

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

Webpack Dashboard

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

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

代码语言:javascript
复制
npm install --save-dev webpack-dashboard
# or
$ yarn add --dev webpack-dashboard

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

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

代码语言:javascript
复制
//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。

代码语言:javascript
复制
"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自带的

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

代码语言:javascript
复制
npm install --save-dev terser-webpack-plugin

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

代码语言:javascript
复制
//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

代码语言:javascript
复制
npm install --save-dev optimize-css-assets-webpack-plugin mini-css-extract-plugin css-loader

webpack.config.js.:

代码语言:javascript
复制
//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代码注入脚本标签。这个插件用于开发和生产构建。

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

代码语言:javascript
复制
npm install --save-dev html-webpack-plugin

webpack.config.js:

代码语言:javascript
复制
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文件

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

代码语言:javascript
复制
npm install --save-dev clean-webpack-plugin

webpack.config.js:

代码语言:javascript
复制
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配置这些插件时遇到任何问题,请随时在评论框中发表评论。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-04-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 前端修罗场 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Webpack Dashboard
  • Terser Webpack Plugin
  • Optimize CSS Assets Webpack Plugin
  • HTML Webpack Plugin
  • Clean Webpack Plugin
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档