写作不易,未经作者容许禁止以任何模式转载!
如果感觉文章不错,欢送关注、点赞和分享!
掘金原文链接: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
  • 继续分享技术博文,关注微信公众号