Webpack Plugin

Plugins

Plugins are the backbone of webpack.

Plugins 是扩展器,它丰富了 webpack 本身,针对 loader 结束后,webpack 打包的整个过程,它并不直接操作文件,而是基于事件机制工作,会监听 webpack 打包过程中的某些节点,执行广泛的任务。

插件的用处,对开发者来说就是可以接触到 webpack 构建流程中的各个阶段并劫持做一些代码处理,对使用者来说则是我们可以通过各类插件实现诸如自动生成 HTML 模版 (html-webpack-plugin)、自动压缩图片 (imagemin-webpack-plugin) 等功能。

Plugins使用

var webpack = require('webpack');
// 导入非 webpack 自带默认插件
var DashboardPlugin = require('webpack-dashboard/plugin');

// 在配置中添加插件
module.exports = {
  //...
  plugins: [
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
   // 编译时(compile time)插件
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': '"production"',
    }),
   // webpack-dev-server 强化插件
    new DashboardPlugin(),
    new webpack.HotModuleReplacementPlugin(),
  ],
};
  1. webpack自带默认插件:new webpack.+插件名
  2. 非webpack自带默认插件:需要先安装导入。

附webpack插件列表
https://webpack.js.org/plugins/
附优秀社区插件
https://webpack.js.org/awesome-webpack/#webpack-plugins

常用插件

html-webpack-plugin

const HtmlWebpackPlugin = require('html-webpack-plugin')

plugins: [
  new HtmlWebpackPlugin({
    filename: 'index.html',
    template: path.join(__dirname, '/index.html'),
    minify: {
      // 压缩HTML文件
      removeComments: true, // 移除HTML中的注释
      collapseWhitespace: true, // 删除空白符与换行符
      minifyCSS: true, // 压缩内联css
    },
    inject: true,
  }),
]

inject 有四个选项值
true:默认值,script 标签位于 html 文件的 body 底部
body:script 标签位于 html 文件的 body 底部(同 true)
head:script 标签位于 head 标签内
false:不插入生成的 js 文件,只是单纯的生成一个 html 文件

多页应用打包:

module.exports = {
  //...
  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html',
      filename: 'index.html', //打包后的文件名
      chunks: ['index'],
    }),
    new HtmlWebpackPlugin({
      template: './public/login.html',
      filename: 'login.html', //打包后的文件名
      chunks: ['login'],
    }),
  ],
}

HtmlWebpackPlugin 提供了一个 chunks 的参数,可以接受一个数组,配置此参数仅会将数组中指定的 js 引入到 html 文件中

clean-webpack-plugin

A webpack plugin to remove/clean your build folder(s).

clean-webpack-plugin 用于在打包前清理上一次项目生成的 bundle 文件,它会根据 output.path 自动清理文件夹。

比在package.json 中配置更简洁。

CopyWebpackPlugin

Copies individual files or entire directories to the build directory

new CopyPlugin({
            patterns: [{ from: `${srcPath}/assets/HXWEarth/`, to: path.resolve(__dirname, '../dist/assets/HXWEarth') }],
        })

npm copyfiles 只能复制文件,所以在需要复制多层文件夹时,需要使用该插件。

CompressionWebpackPlugin

Prepare compressed versions of assets to serve them with Content-Encoding.

该插件帮助我们在构建时生成压缩文件用于gzip。相当于静态压缩。

const CompressionPlugin = require('compression-webpack-plugin')

plugins: [
  new CompressionPlugin({
    // gzip压缩配置
    test: /\.js$|\.html$|\.css/, // 匹配文件名
    threshold: 10240, // 对超过10kb的数据进行压缩
    deleteOriginalAssets: false, // 是否删除原文件
  }),
]

动态压缩是仅仅通过nginx.conf来进行配置,但是动态压缩过程占用cpu的资源,压缩比越高cpu占用越高,所以请配置合适的压缩比。

gzip             on;
gzip_min_length  1000;
gzip_proxied     expired no-cache no-store private auth;
gzip_types       text/plain application/xml;

gzip 对基于文本格式文件的压缩效果最好(如:CSS、JavaScript 和 HTML),在压缩较大文件时往往可实现高达 70-90% 的压缩率,对已经压缩过的资源(如:图片)进行 gzip 压缩处理,效果很不好。

DefinePlugin

定义全局变量

new webpack.DefinePlugin({
   DESCRIPTION: 'This Is The Test Text.',
 })

插件详解

插件向第三方开发者提供了 webpack 引擎中完整的能力。使用阶段式的构建回调,开发者可以引入它们自己的行为到 webpack 构建流程中。

插件组成:

  • 一个 JavaScript 函数或 JavaScript 类,用于承接这个插件模块的所有逻辑;
  • 在它原型上定义的 apply 方法,会在安装插件时被调用,并被 webpack compiler 调用一次;
  • 指定一个触及到 webpack 本身的事件钩子,即下文会提及的 hooks,用于特定时机处理额外的逻辑;
  • 对 webpack 实例内部做一些操作处理;
  • 在功能流程完成后可以调用 webpack 提供的回调函数;
  • A named JavaScript function or a JavaScript class.
  • Defines apply method in its prototype.
  • Specifies an event hook to tap into.
  • Manipulates webpack internal instance specific data.
  • Invokes webpack provided callback after functionality is complete.
// A JavaScript class.
class MyExampleWebpackPlugin {
  // Define `apply` as its prototype method which is supplied with compiler as its argument
  apply(compiler) {
    // Specify the event hook to attach to
    compiler.hooks.emit.tapAsync(
      'MyExampleWebpackPlugin',
      (compilation, callback) => {
        console.log('This is an example plugin!');
        console.log(
          'Here’s the `compilation` object which represents a single build of assets:',
          compilation
        );

        // Manipulate the build using the plugin API provided by webpack
        compilation.addModule(/* ... */);

        callback();
      }
    );
  }
}

compiler:包含了 webpack 环境所有的的配置信息,包含 options,loaders,plugins 这些信息,这个对象在 webpack 启动时候被实例化,它是全局唯一的,可以简单地把它理解为 webpack 实例。compiler 钩子列表可参见官方文档。
https://webpack.js.org/api/compiler-hooks/

compilation:包含了当前的模块资源、编译生成资源、变化的文件等。当 webpack 以开发模式运行时,每当检测到一个文件变化,一次新的 compilation 将被创建。compilation 对象也提供了很多事件回调供插件做扩展。通过 compilation 也能读取到 compiler 对象。两者的区别在于,前者代表了整个 webpack 从启动到关闭的生命周期,而 compilation 只代表一次单独的编译。
https://webpack.js.org/api/compilation-hooks/

你可能感兴趣的:(Webpack Plugin)