分享好友 前端技术首页 频道列表

webpack之tapable

webpack  2023-03-08 19:450

webpack之tapable

tapable

webpack本质上是一种事件流的机制,它的工作流程就是将各个插件串联起来,而实现这一切的核心就是tapable,核心原理是依赖于发布订阅模式;
tapable注册函数的方法有三种:tap、tapAsync、tapPromise
相对应的执行方法也有三种:call、callAsync、promise

SyncHook

const { SyncLoopHook } = require('tapable')

class Lesson {
  constructor () {
    this.index = 0
    this.hooks = {
      arch: new SyncLoopHook(['name'])
    }
  }
  tap () {
    let self = this
    this.hooks.arch.tap('node', function (name) {
      console.log('node', name)
      return ++self.index >=3 ? undefined :'23'
    })
    this.hooks.arch.tap('react', function (name) {
      console.log('react', name)
    })
  }
  start () {
    this.hooks.arch.call('jw')
  }
}

let l = new Lesson()
l.tap()
l.start()
  • SyncBailHook

SyncBailHook同步熔断保险钩子,即return一个非undefined的值,则不再继续执行后面的监听函数

  • SyncWaterfallHook

上一个监听函数的返回值会传递给下一个监听函数

  • SyncLoopHook

遇到某个不返回undefined的监听函数,就重复执行


AsyncHook

const { AsyncParallelHook } = require('tapable')

class Lesson {
  constructor () {
    this.index = 0
    this.hooks = {
      arch: new AsyncParallelHook(['name'])
    }
  }
  tap () {
    let self = this
    this.hooks.arch.tapAsync('node', function (name, cb) {
      setTimeout(() => {
        console.log('node', name)
        cb()
      })
    })
    this.hooks.arch.tapAsync('react', function (name, cb) {
      console.log('react', name)
      cb()
    })
  }
  start () {
    this.hooks.arch.callAsync('jw', function () {
      console.log('end')
    })
  }
}

let l = new Lesson()
l.tap()
l.start()

结果:
react jw
node jw
end
  • AsyncParallelHook

异步 并行

源码:

module.exports =  class AsyncParallelHook {
  constructor () {
    this.tasks = []
  }
  tapAsync (name, fn) {
    this.tasks.push(fn)
  }
  callAsync (...args) {
    const final = args.pop()
    let index = 0
    const done = () => {
      index++
      if (index === this.tasks.length) {
        final()
      }
    }
    this.tasks.forEach(task => {
      task(...args, done)
    })
  }
}
  • AsyncSeriesHook

异步串行

源码:

// callback方式
module.exports =  class AsyncSerieslHook {
  constructor () {
    this.tasks = []
  }
  tapAsync (name, fn) {
    this.tasks.push(fn)
  }
  callAsync (...args) {
    let index = 0
    const final = args.pop()
    const next = () => {
      if (this.tasks.length === index) {
        final()
        return
      }
      const firstFn = this.tasks[index++]
      firstFn(...args, next)
    }
    next()
  }
}


// promise方式
module.exports =  class AsyncSerieslHook {
  constructor () {
    this.tasks = []
  }
  tapPromise (name, fn) {
    this.tasks.push(fn)
  }
  promise (...args) {
    const [firstFn, ...others] = this.tasks
    return others.reduce((n, p) => {
      return n.then(_ => p(...args))
    }, firstFn(...args))
  }
}

调用:

//callback方式调用
const AsyncSeriesHook = require('./asyncHook')

class Lesson {
  constructor () {
    this.index = 0
    this.hooks = {
      arch: new AsyncSeriesHook(['name'])
    }
  }
  tap () {
    this.hooks.arch.tapAsync('node', function (name, cb) {
      setTimeout(() => {
        console.log('node', name)
        cb()
      }, 1000)
    })
    this.hooks.arch.tapAsync('react', function (name, cb) {
      setTimeout(() => {
        console.log('react', name)
        cb()
      }, 2000)
    })
  }
  start () {
    this.hooks.arch.callAsync('jw', function () {
      console.log('end')
    })
  }
}

let l = new Lesson()
l.tap()
l.start()

// promise方式调用
const AsyncSeriesHook = require('./asyncHook')

class Lesson {
  constructor () {
    this.index = 0
    this.hooks = {
      arch: new AsyncSeriesHook(['name'])
    }
  }
  tap () {
    this.hooks.arch.tapPromise('node', function (name) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('node', name)
          resolve()
        }, 1000)
      })
    })
    this.hooks.arch.tapPromise('react', function (name) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('react', name)
          resolve()
        }, 2000)
      })
    })
  }
  start () {
    this.hooks.arch.promise('jw').then(function () {
      console.log('end')
    })
    // this.hooks.arch.callAsync('jw', function () {
    //   console.log('end')
    // })
  }
}

let l = new Lesson()
l.tap()
l.start()
  • AsyncSeriesWaterFallHook

异步 串行 结果传递,错误处理


callback方式:

// callback 方式
class Hook {
  constructor () {
    this.tasks = []
  }
  tapAsync(name, fn) {
    this.tasks.push(fn)
  }
  callAsync(...args) {
    let index = 0
    const final = args.pop()
    const next = (err, data) => {
      const task = this.tasks[index]
      if (!task) return final()
      if (index === 0) {
        task(...args, next)
      } else if (index > 0) {
        if (!err && data) {
          task(data, next)
        }
        if (!err && !data) {
          task(...args, next)
        }
        if (err) {
          final(err)
        }
      }
      index++
    }
    next()
  }
}

module.exports = Hook

// 调用
// const { AsyncSeriesWaterfallHook } = require('tapable')
const AsyncSeriesWaterfallHook = require('./hook')

class Lesson {
  constructor () {
    this.hooks = {
      arch: new AsyncSeriesWaterfallHook()
    }
  }

  tap () {
    this.hooks.arch.tapAsync('lesson1', function (name, cb) {
      setTimeout(() => {
        console.log('lesson1', name)
        /** 第一次参数是err, 第二个参数是传递给下一步的参数 */
        cb(null, 'werw')
      }, 1000)
    })
    this.hooks.arch.tapAsync('lesson2', function (name, cb) {
      setTimeout(() => {
        console.log('lesson2', name)
        cb()
      }, 2000)
    })
  }
  call () {
    this.hooks.arch.callAsync(['rain'], (err) => {
      console.log(err)
      console.log('end')
    })
  }
}

const le = new Lesson()

le.tap()
le.call()

promise方式:

// promise方式

class Hook {
  constructor () {
    this.tasks = []
  }
  tapPromise(name, fn) {
    this.tasks.push(fn)
  }
  promise(...args) {
    const [first, ...others] = this.tasks
    return others.reduce((p, n) => p.then(_ => n(_)), first(...args))
  }
}

module.exports = Hook

// 调用

// const { AsyncSeriesWaterfallHook } = require('tapable')
const AsyncSeriesWaterfallHook = require('./hook')

class Lesson {
  constructor () {
    this.hooks = {
      arch: new AsyncSeriesWaterfallHook()
    }
  }

  tap () {
    this.hooks.arch.tapPromise('lesson1', function (name) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('lesson1', name)
          /** 第一次参数是err, 第二个参数是传递给下一步的参数 */
          resolve('aa')
        }, 1000)
      })
    })
    this.hooks.arch.tapPromise('lesson2', function (name) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('lesson2', name)
          resolve()
        }, 2000)
      })
    })
  }
  call () {
    this.hooks.arch.promise(['rain']).then((data) => {
      console.log(data)
      console.log('end')
    })
  }
}

const le = new Lesson()

le.tap()
le.call()

查看更多关于【webpack】的文章

展开全文
相关推荐
反对 0
举报 0
评论 0
图文资讯
热门推荐
优选好物
更多热点专题
更多推荐文章
webpack命令局部运行的几种方法 webpack用法
webpack命令局部运行的几种方法 1. 第一种,先全局安装webpack命令:npm install -g webpack然后再在项目内安装命令:npm install webpack --save-dev这样在项目内就可以直接使用webpack命令了,运行的却是局部的webpack 2.第二种,直接在局部安装webpack,

0评论2023-03-08476

扩大编译内存 webpack-dev-server --inline --progress --config build/webpack.dev.conf.js
 verbose stack Error: choreographer@1.0.0 rundev: `webpack-dev-server --inline --progress --config build/webpack.dev.conf.js`扩大编译内存 地址  D:\park\node_modules\.bin\webpack-dev-server.cmd@ECHO offSETLOCALCALL :find_dp0IF EXIST "%dp0

0评论2023-03-08496

html-webpack-plugin不输出script标签的方法 htmlwebpackplugin chunks
约550行:if (!this.options.disableScript) {if (this.options.inject === 'head') {head = head.concat(scripts);} else {body = body.concat(scripts);}}然后这样使用:new HtmlWebpackPlugin({disableScript: true,//...})

0评论2023-03-08586

gulp与webpack-stream集成配置 grunt gulp webpack区别
webpack非常强大,但是也有不足的地方,批量式处理依然是gulp更胜一筹.我们是否可以将两者的优点结合起来呢? 这篇文章就是讲述如何集成gulp和webpack1.安装webpack-stream很重要的插件,当然也可以直接使用官方的webpack,集成方式可以看webpack官网. 但webpack-s

0评论2023-03-08858

【Vue】WebPack 忽略指定文件或目录
前端Vue项目使用 WebPack 打包时,有时候我们需要忽略掉一些文件。比如一些说明文档、ReadMe之类的,我们只希望它存在于源码中,而不是被打包给用户。通过修改 webpack.base.conf.js 配置文件,有以下方式可以达到目的。方法1:使用 null-loadermodule: {rule

0评论2023-03-08539

Karma 4 - Karma 集成 Webpack 进行单元测试
 可以将 karma 与 webpack 结合起来,自动化整个单元测试过程。1. 首先根据 1 完成基本的 karma 测试环境。2. 安装 webpack 和 webpack 使用的 loader在最简单的情况下,我们只需要 webpack 和 webpack 的 karma 插件 karma-webpacknpm i -D webpack karma-w

0评论2023-03-08430

webpack的实现机制

0评论2023-03-08425

转-webpack学习笔记--整体配置结构 webpack的配置哪些参数
前端学习一段时间后,尤其是工作2-3年的小伙伴们在面试中都会害怕被问到webpack,我也害怕,每次都是临时抱佛脚,虽然自己会简单的配置webpack但是对webpack的原理还是一知半解,无意中看到这篇文章写的还不错,所以转发过来,也方便自己学习和记录。const pat

0评论2023-03-08550

vscode配置webpack alias支持
安装node modules resolve插件添加jsconfig配置https://code.visualstudio.com/docs/languages/jsconfig{"compilerOptions": {"target": "es2017","allowSyntheticDefaultImports": false,"baseUrl": "./","paths&

0评论2023-03-08374

Webpack 傻瓜式指南(一)
modules with dependencies   webpack   module bundler   static  assetss   .js .js .png Webpack傻瓜式指南npm install -g webpack定义   MODULE BUNDLER 把有依赖关系的各种文件打包成一系列的静态资源简单来说就是一个配置文件, 在这一个文件中

0评论2023-03-08900

Webpack
Webpack 是加强版Browserify大型单页应用React Webpack 专家用户所有的静态文件jade   png  所有静态模块认为是module  .js  .pngcode splitting   loadercode splitting 可以自动完成, 不需要手动处理loader 处理各种类型的静态文件, 并且支持串联

0评论2023-03-08606

webpack(5)配置打包less和sass webpack打包lib
1.打包less需要下载包less和less-loader:npm install less less-loader -D2.打包sass需要下载包node-sass和sass-loader:npm install node-sass sass-loader -D3.在(4)的基础上新增一个index.less文件:@width:200px;@height:200px;@color:green;#box1{

0评论2023-03-08651

更多推荐