Webpack Plugin知识分享

390次阅读  |  发布于2年以前

认识Plugin

常用Plugin

CleanWebpackPlugin

安装:

配置:


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

安装

配置

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>

效果

DefinePlugin

用于定义全局常量

安装

配置

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

安装:

配置:

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

Tapable Hook分类

Hook的使用过程

  1. 创建Hook对象

2 . 注册Hook中的事件

3 . 触发事件

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文件夹吧。

const AutoUploadPlugin = require("../plugins/autoUploadPlugin")

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

a . 通过compiler对象调用hooks注册事件

b . 通过compilation对象获取打包输出文件夹路径

c . 建立ssh连接

d . 删除远程服务器中原本的内容

e . 上传生成后的文件到服务器

f . 关闭ssh连接

g . 执行回调

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

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8