写作不易,未经作者允许禁止以任何形式转载!
如果觉得文章不错,欢迎关注、点赞和分享!
掘金原文链接

认识 Plugin

  • Loader 是用于特定的模块类型进行转换;

  • Plugin 可以用于执行更加广泛的任务,比如打包优化、资源管理、环境变量注入等;

常用 Plugin

CleanWebpackPlugin

  • 每次修改了一些配置,重新打包时,都需要手动删除 dist 文件夹:

  • 我们可以借助于一个插件来帮助我们完成,这个插件就是 CleanWebpackPlugin;

安装:

  • npm install clean-webpack-plugin --save

配置:

const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
entry: "./src/js/main.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "build"),
},
module: {...},
plugins: [new CleanWebpackPlugin()],
};

HtmlWebpackPlugin

  • 我们的 HTML 文件是编写在根目录下的,而最终打包的 dist 文件夹中是没有 index.html 文件的。

  • 在进行项目部署的时,必然也是需要有对应的入口文件 index.html;

  • 所以我们也需要对 index.html 进行打包处理;

安装

  • npm install html-webpack-plugin --save

配置

  • 可传入变量例如 title,

  • 可自定义模板,template 填写模板路径

const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
entry: "./src/js/main.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "build"),
},
module: {...},
plugins: [
new HtmlWebpackPlugin({
title: "LeBronChao Webpack",
template: "./public/index.html",
}),
],
};

模板和变量引用方法

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<h1>LeBronChao Webpack</h1>
</body>
</html>

效果

  • 现在自动在 build 文件夹中,生成了一个 index.html 的文件

  • 该文件中也自动添加了我们打包的 bundle.js 文件

  • 这个文件是如何生成的呢?

    • 默认情况下是根据 ejs 的一个模板来生成的;
    • 在 html-webpack-plugin 的源码中,有一个 default_index.ejs 模块;

DefinePlugin

用于定义全局常量

安装

  • Webpack 内置,无需安装

配置

const { DefinePlugin } = require("webpack");

module.exports = {
entry: "./src/js/main.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "build"),
},
module: {...},
plugins: [
new DefinePlugin({
BASE_URL: "'./favicon.ico'",
}),
],
};

注意事项:

  1. 定义的变量赋值时若为字符串需嵌套字符串,若为变量在""内填写变量,如上。

模板中的使用方法

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title><%= htmlWebpackPlugin.options.title %></title>
<link rel="icon" href="<%= BASE_URL %>" />
</head>
<body>
<h1>LeBronChao Webpack</h1>
</body>
</html>

CopyWebpackPlugin

  • 在 vue 的打包过程中,如果我们将一些文件放到 public 的目录下,那么这个目录会被复制到 dist 文件夹中。
    • 这个复制的功能,我们可以使用 CopyWebpackPlugin 来完成;

安装:

  • npm install copy-webpack-plugin --save

配置:

  • 复制的规则在 patterns 中设置;

  • from:设置从哪一个源中开始复制;

  • to:复制到的位置,可以省略,会默认复制到打包的目录下,路径编写以打包目录为根目录;

  • globOptions:设置一些额外的选项,其中 ignore 可以编写需要忽略的文件:

    • DS_Store:mac 目录下会自动生成的一个文件;
    • index.html:也不需要复制,因为我们已经通过 HtmlWebpackPlugin 完成了 index.html 的生成;
const CopyWebpackPlugin = require("copy-webpack-plugin");

module.exports = {
entry: "./src/js/main.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "build"),
},
module: {...},
plugins: [
new CopyWebpackPlugin({
patterns: [
{
from: "public",
// 可不写,默认到output
to: "build",
globOptions: {
ignore: ["**/index.html", "**/.DS_Store", "**/abc.txt"],
},
},
],
}),
],
};

自定义 Plugin

  • webpack 有两个非常重要的类 Compiler 和 Compilation

    • 他们通过注入插件的方式,来监听 webpack 的所有生命周期
    • 插件的注入离不开各种各样的 Hook
    • Hook 来源于 Tapable 库
  • 想自定义 Plugin,先了解一个库 Tapable

    • Tapable 是官方编写和维护的一个库
    • Tapable 是管理着需要的 Hook,这些 Hook 可以应用到插件中

Tapable Hook 分类

  • 同步 Sync

    • SyncHook
    • SyncBailHook
    • SyncWaterfallHook
    • SyncLoopHook
  • 异步 Async

    • Paralle(并行)
      • AsyncPrarllelHook
      • AsyncParallelBailHook
    • Series(串行)
      • AsyncSeriesHook
      • AsyncSeriesBailHook
      • AsyncSeriresWaterfallHook
    • 同步和异步的
      • 以 sync 开头的为同步 hook
      • 以 async 开头的,两个事件处理回调,不会等待上一次处理回调结束后再执行下一次回调。
  • 其他的类别

    • baill:当有返回值时,就不会执行后续的事件触发了。
    • Loop:当返回值为 true 时,就会反复执行该事件,当返回值为 undefined 或者不返回内容时,退出事件
    • Waterfall:当返回值不为 undefined 时,会将这次返回的结果作为下次事件的第一个参数
    • Parallel:并行,会同时执行事件处理回调的 Hook
    • Series:串行,会等待上一事件处理回调的 Hook

Hook 的使用过程

  1. 创建 Hook 对象

    • New 对象传入的数组为需传入参数 key
  2. 注册 Hook 中的事件

  3. 触发事件

  • plugin.js
const { SyncWaterfallHook } = require('tapable');

class tapableTest {
constructor() {
this.hooks = {
syncHook: new SyncWaterfallHook(['name', 'age']),
};

this.hooks.syncHook.tap('event1', (name, age) => {
console.log('event1', name, age);
return 'event1';
});

this.hooks.syncHook.tap('event2', (name, age) => {
console.log('event2', name, age);
});
}

emit() {
this.hooks.syncHook.call('lebron', 21);
}
}

const index = new tapableTest();
index.emit();

// event1 lebron 21
// event2 event1 21

自定义一个 AutoUploadPlugin

前端开发完成后,经常要打包上传代码。个人开发者一般会使用 Nginx 部署服务,每次上传代码太麻烦了,自己写个 Plugin 让他自动上传到 Nginx 文件夹吧。

  • plugin 配置
    • host:主机地址
    • username:主机用户名
    • password:主机 ssh 登录密码
    • remotePath:远程部署服务的文件夹
const AutoUploadPlugin = require('../plugins/autoUploadPlugin');

plugins: [
new HtmlWebpackPlgin(),
new AutoUploadPlugin({
host: 'xx.xx.xx.xx',
username: 'root',
password: 'xxxxxxx',
remotePath: '/test',
}),
];
  • AutoUploadPlugin.js

    • 借助 node-ssh 库完成远程系列操作

      1. npm i node-ssh
    • Constructor

      1. 生成 ssh 对象

      2. 接收 options 参数-

    • 每个 Plugin 都需要一个 apply 函数来注册插件

      1. 通过 compiler 对象调用 hooks 注册事件
      2. 通过 compilation 对象获取打包输出文件夹路径
      3. 建立 ssh 连接
      4. 删除远程服务器中原本的内容
      5. 上传生成后的文件到服务器
      6. 关闭 ssh 连接
      7. 执行回调
const { NodeSSH } = require('node-ssh');

class AutoUploadPlugin {
constructor(options) {
this.ssh = new NodeSSH();
this.options = options;
}

apply(compiler) {
// 使用文件生成后的钩子
compiler.hooks.afterEmit.tapAsync(
'AutoUploadPlugin',
async (compilation, callback) => {
// 1. 获取输出的文件夹路径
const outputPath = compilation.outputOptions.path;

// 2. 连接服务器(ssh)
await this.connectServer();

// 3. 删除原来目录中的内容
const serverDir = this.options.remotePath;
await this.ssh.execCommand(`rm -rf ${serverDir}/*`);

// 4. 上传文件到服务器
await this.uploadFiles(outputPath, serverDir);

// 5. 关闭SSH
this.ssh.dispose();

callback();
}
);
}

async connectServer() {
await this.ssh.connect({
host: this.options.host,
username: this.options.username,
password: this.options.password,
});
}

async uploadFiles(localPath, remotePath) {
const status = await this.ssh.putDirectory(localPath, remotePath, {
// 递归上传所有文件
recursive: true,
// 并发数
concurrency: 10,
});
console.log('Upload ' + status ? '成功' : '失败');
}
}

module.exports = AutoUploadPlugin;

掘金原文链接

掘金:前端 LeBron

知乎:前端 LeBron

持续分享技术博文,关注微信公众号 👇🏻

img