关于webpack:Webpack-Plugin知识分享

0次阅读

共计 5050 个字符,预计需要花费 13 分钟才能阅读完成。

写作不易,未经作者容许禁止以任何模式转载!
如果感觉文章不错,欢送关注、点赞和分享!
掘金原文链接:Webpack Plugin 常识分享

意识 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
  • 掘金原文链接:Webpack Plugin 常识分享
  • 掘金:前端 LeBron
  • 知乎:前端 LeBron
  • 继续分享技术博文,关注微信公众号👇🏻

正文完
 0