webpack4 plugins 篇


demo 代碼點此,篇幅有限,僅介紹幾個常用的。

start


什么是 plugins ?

While loaders are used to transform certain types of modules, plugins can be leveraged to perform a wider range of tasks like bundle optimization, asset management and injection of environment variables.

plugins 可用於執行范圍更廣的任務,如打包優化,資源管理和重新定義環境中的變量。

HtmlWebpackPlugin


該插件將為你生成一個 HTML5 文件, 並幫你引入 webpack 打包好的 js 等文件.

安裝:

npm i -D html-webpack-plugin

在 webpack.config.js 中配置:

const path = require('path');
+ const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  // mode: 'production',
  mode: 'development',
  // 入口
  // entry: './src/index.js',
  entry: {
    main: './src/index.js',
  },
  module: {...},
+  plugins: [
+    new HtmlWebpackPlugin({
+      title: 'webpack4 plugins 篇',
+      template: './src/index.html'
+    }),
+  ],
  // 出口
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
}

然后在 src 目錄下創建 index.html 作為模板:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
  <div id="root"></div>
</body>
</html>

CleanWebpackPlugin


用於刪除/清除構建文件夾的 webpack 插件,其實就是打包前先把 dist 文件夾清空。

依然是安裝:

npm i -D clean-webpack-plugin

然后配置:

// webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
+ const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: {
    main: './src/index.js',
  },
  module: {...},
  plugins: [
    new HtmlWebpackPlugin({
      title: 'webpack4 plugins 篇',
      template: './src/index.html'
    }),
+    new CleanWebpackPlugin(),
  ],
  // 出口
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
}

HotModuleReplacementPlugin


模塊熱替換插件,即 HMR,webpack4 自帶插件,無需安裝,在開發者模式下配合devServer使用。

注意: 永遠不要在生產環境(production)下啟用 HMR

安裝 webpack-dev-server:

npm i -D webpack-dev-server

配置:

// webpack.config.js

...
+ const webpack = require('webpack');

module.exports = {
  mode: 'development',
  entry: {
    main: './src/index.js',
  },
  module: {...},
  plugins: [
    new HtmlWebpackPlugin({
      title: 'webpack4 plugins 篇',
      template: './src/index.html'
    }),
    new CleanWebpackPlugin(),
+   new webpack.HotModuleReplacementPlugin(),
  ],
+  devServer: {
+    contentBase: path.resolve(__dirname, "dist"),
+    // 啟用 gzip
+    compress: true,
+		 open: true,
+    port: 9000,
+    hot: true,
+    hotOnly: true,
+  },
  // 出口
  output: {...},
}

然后在 package.josn 中的 script 里配置命令,方便實用。

// package.json
...
"scripts": {
+ "start": "webpack-dev-server",
  "bundle": "webpack"
},
...

然后跑命令:

npm start

接着修改 index.less,切回瀏覽器,你會發現 css 效果已經改了。

可以試試修改 js 模塊看看效果,修改 index.js:

// index.js
// 在最后面加上這段代碼

...
+ if (module.hot) {
+   module.hot.accept('./components/Header', () => {
+     Header();
+   })
+ }

然后重新啟動 webpack-dev-server,再修改 Header.js:

// Header.js

...
header.innerText = '修改后的header';
...

再切回瀏覽器,你會發現新增了一個修改過的 Header。

miniCssExtractPlugin


mini-css-extract-plugin 將CSS提取到單獨的文件中,類似功能的有 extract-text-webpack-plugin(已廢棄),兩者相比,mini-css-extract-plugin 的優點:

  • 異步加載
  • 沒有重復的編譯(性能)
  • 更容易使用
  • 特定於CSS

安裝:

npm i -D mini-css-extract-plugin

然后配置:

// webpack.config.js

...
+ const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  mode: 'development',
  entry: {...},
  module: {
    rules: [
    ...
    {
      // 打包 css、less
      test: /\.(css|less)$/,
      use: [
        // 這里一定要加
 +       {
 +         loader: MiniCssExtractPlugin.loader,
 +       },
        {
          loader: 'css-loader',
          options: {
            importLoaders: 2,
          }
        },
        'less-loader',
        'postcss-loader',
      ],
    }],
  },
  plugins: [
    ...
+    new MiniCssExtractPlugin({
+      filename: 'css/[name].css',
+     chunkFilename: 'css/[id].css',
+    }),
  ],
  devServer: {...},
  // 出口
  output: {...},
}

接着執行npm run bundle打包,你會發現 css 都打包起來了。

PurgecssPlugin


可以去除未使用的 css,一般與 glob、glob-all 配合使用。

安裝:

npm i -D purgecss-webpack-plugin glob

配置:

// webpack.config.js

...
+ const glob = require('glob');
+ const PurgecssPlugin = require('purgecss-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: {...},
  module: {...},
  plugins: [
    ...
+    new PurgecssPlugin({
+      paths: glob.sync(`${path.join(__dirname, 'src')}/**/*`, 
+      { 
+        // 不匹配目錄,只匹配文件
+        nodir: true,
+      }),
+    }),
  ],
  devServer: {...},
  // 出口
  output: {...},
}

optimizeCssAssetsWebpackPlugin


在 production 下打包,js 文件是會自動壓縮的,但 css 不會,所以使用 optimize-css-assets-webpack-plugin 進行壓縮 css。

安裝:

npm i -D optimize-css-assets-webpack-plugin

配置:

// webpack.config.js

...
+ const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: {...},
  module: {...},
  plugins: [
    ...
+   new OptimizeCssAssetsPlugin(),
  ],
  devServer: {...},
  // 出口
  output: {...},
}

打包后,你會發現 css 文件都壓縮好了。

備注


篇幅有限,所以就不多 bb 了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM