• Stars
    star
    3,668
  • Rank 11,532 (Top 0.3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 11 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Just a little module for plugins.

Tapable

The tapable package expose many Hook classes, which can be used to create hooks for plugins.

const {
	SyncHook,
	SyncBailHook,
	SyncWaterfallHook,
	SyncLoopHook,
	AsyncParallelHook,
	AsyncParallelBailHook,
	AsyncSeriesHook,
	AsyncSeriesBailHook,
	AsyncSeriesWaterfallHook
 } = require("tapable");

Installation

npm install --save tapable

Usage

All Hook constructors take one optional argument, which is a list of argument names as strings.

const hook = new SyncHook(["arg1", "arg2", "arg3"]);

The best practice is to expose all hooks of a class in a hooks property:

class Car {
	constructor() {
		this.hooks = {
			accelerate: new SyncHook(["newSpeed"]),
			brake: new SyncHook(),
			calculateRoutes: new AsyncParallelHook(["source", "target", "routesList"])
		};
	}

	/* ... */
}

Other people can now use these hooks:

const myCar = new Car();

// Use the tap method to add a consument
myCar.hooks.brake.tap("WarningLampPlugin", () => warningLamp.on());

It's required to pass a name to identify the plugin/reason.

You may receive arguments:

myCar.hooks.accelerate.tap("LoggerPlugin", newSpeed => console.log(`Accelerating to ${newSpeed}`));

For sync hooks, tap is the only valid method to add a plugin. Async hooks also support async plugins:

myCar.hooks.calculateRoutes.tapPromise("GoogleMapsPlugin", (source, target, routesList) => {
	// return a promise
	return google.maps.findRoute(source, target).then(route => {
		routesList.add(route);
	});
});
myCar.hooks.calculateRoutes.tapAsync("BingMapsPlugin", (source, target, routesList, callback) => {
	bing.findRoute(source, target, (err, route) => {
		if(err) return callback(err);
		routesList.add(route);
		// call the callback
		callback();
	});
});

// You can still use sync plugins
myCar.hooks.calculateRoutes.tap("CachedRoutesPlugin", (source, target, routesList) => {
	const cachedRoute = cache.get(source, target);
	if(cachedRoute)
		routesList.add(cachedRoute);
})

The class declaring these hooks need to call them:

class Car {
	/**
	  * You won't get returned value from SyncHook or AsyncParallelHook,
	  * to do that, use SyncWaterfallHook and AsyncSeriesWaterfallHook respectively
	 **/

	setSpeed(newSpeed) {
		// following call returns undefined even when you returned values
		this.hooks.accelerate.call(newSpeed);
	}

	useNavigationSystemPromise(source, target) {
		const routesList = new List();
		return this.hooks.calculateRoutes.promise(source, target, routesList).then((res) => {
			// res is undefined for AsyncParallelHook
			return routesList.getRoutes();
		});
	}

	useNavigationSystemAsync(source, target, callback) {
		const routesList = new List();
		this.hooks.calculateRoutes.callAsync(source, target, routesList, err => {
			if(err) return callback(err);
			callback(null, routesList.getRoutes());
		});
	}
}

The Hook will compile a method with the most efficient way of running your plugins. It generates code depending on:

  • The number of registered plugins (none, one, many)
  • The kind of registered plugins (sync, async, promise)
  • The used call method (sync, async, promise)
  • The number of arguments
  • Whether interception is used

This ensures fastest possible execution.

Hook types

Each hook can be tapped with one or several functions. How they are executed depends on the hook type:

  • Basic hook (without β€œWaterfall”, β€œBail” or β€œLoop” in its name). This hook simply calls every function it tapped in a row.

  • Waterfall. A waterfall hook also calls each tapped function in a row. Unlike the basic hook, it passes a return value from each function to the next function.

  • Bail. A bail hook allows exiting early. When any of the tapped function returns anything, the bail hook will stop executing the remaining ones.

  • Loop. When a plugin in a loop hook returns a non-undefined value the hook will restart from the first plugin. It will loop until all plugins return undefined.

Additionally, hooks can be synchronous or asynchronous. To reflect this, there’re β€œSync”, β€œAsyncSeries”, and β€œAsyncParallel” hook classes:

  • Sync. A sync hook can only be tapped with synchronous functions (using myHook.tap()).

  • AsyncSeries. An async-series hook can be tapped with synchronous, callback-based and promise-based functions (using myHook.tap(), myHook.tapAsync() and myHook.tapPromise()). They call each async method in a row.

  • AsyncParallel. An async-parallel hook can also be tapped with synchronous, callback-based and promise-based functions (using myHook.tap(), myHook.tapAsync() and myHook.tapPromise()). However, they run each async method in parallel.

The hook type is reflected in its class name. E.g., AsyncSeriesWaterfallHook allows asynchronous functions and runs them in series, passing each function’s return value into the next function.

Interception

All Hooks offer an additional interception API:

myCar.hooks.calculateRoutes.intercept({
	call: (source, target, routesList) => {
		console.log("Starting to calculate routes");
	},
	register: (tapInfo) => {
		// tapInfo = { type: "promise", name: "GoogleMapsPlugin", fn: ... }
		console.log(`${tapInfo.name} is doing its job`);
		return tapInfo; // may return a new tapInfo object
	}
})

call: (...args) => void Adding call to your interceptor will trigger when hooks are triggered. You have access to the hooks arguments.

tap: (tap: Tap) => void Adding tap to your interceptor will trigger when a plugin taps into a hook. Provided is the Tap object. Tap object can't be changed.

loop: (...args) => void Adding loop to your interceptor will trigger for each loop of a looping hook.

register: (tap: Tap) => Tap | undefined Adding register to your interceptor will trigger for each added Tap and allows to modify it.

Context

Plugins and interceptors can opt-in to access an optional context object, which can be used to pass arbitrary values to subsequent plugins and interceptors.

myCar.hooks.accelerate.intercept({
	context: true,
	tap: (context, tapInfo) => {
		// tapInfo = { type: "sync", name: "NoisePlugin", fn: ... }
		console.log(`${tapInfo.name} is doing it's job`);

		// `context` starts as an empty object if at least one plugin uses `context: true`.
		// If no plugins use `context: true`, then `context` is undefined.
		if (context) {
			// Arbitrary properties can be added to `context`, which plugins can then access.
			context.hasMuffler = true;
		}
	}
});

myCar.hooks.accelerate.tap({
	name: "NoisePlugin",
	context: true
}, (context, newSpeed) => {
	if (context && context.hasMuffler) {
		console.log("Silence...");
	} else {
		console.log("Vroom!");
	}
});

HookMap

A HookMap is a helper class for a Map with Hooks

const keyedHook = new HookMap(key => new SyncHook(["arg"]))
keyedHook.for("some-key").tap("MyPlugin", (arg) => { /* ... */ });
keyedHook.for("some-key").tapAsync("MyPlugin", (arg, callback) => { /* ... */ });
keyedHook.for("some-key").tapPromise("MyPlugin", (arg) => { /* ... */ });
const hook = keyedHook.get("some-key");
if(hook !== undefined) {
	hook.callAsync("arg", err => { /* ... */ });
}

Hook/HookMap interface

Public:

interface Hook {
	tap: (name: string | Tap, fn: (context?, ...args) => Result) => void,
	tapAsync: (name: string | Tap, fn: (context?, ...args, callback: (err, result: Result) => void) => void) => void,
	tapPromise: (name: string | Tap, fn: (context?, ...args) => Promise<Result>) => void,
	intercept: (interceptor: HookInterceptor) => void
}

interface HookInterceptor {
	call: (context?, ...args) => void,
	loop: (context?, ...args) => void,
	tap: (context?, tap: Tap) => void,
	register: (tap: Tap) => Tap,
	context: boolean
}

interface HookMap {
	for: (key: any) => Hook,
	intercept: (interceptor: HookMapInterceptor) => void
}

interface HookMapInterceptor {
	factory: (key: any, hook: Hook) => Hook
}

interface Tap {
	name: string,
	type: string
	fn: Function,
	stage: number,
	context: boolean,
	before?: string | Array
}

Protected (only for the class containing the hook):

interface Hook {
	isUsed: () => boolean,
	call: (...args) => Result,
	promise: (...args) => Promise<Result>,
	callAsync: (...args, callback: (err, result: Result) => void) => void,
}

interface HookMap {
	get: (key: any) => Hook | undefined,
	for: (key: any) => Hook
}

MultiHook

A helper Hook-like class to redirect taps to multiple other hooks:

const { MultiHook } = require("tapable");

this.hooks.allHooks = new MultiHook([this.hooks.hookA, this.hooks.hookB]);

More Repositories

1

webpack

A bundler for javascript and friends. Packs many modules into a few bundled assets. Code Splitting allows for loading parts of the application on demand. Through "loaders", modules can be CommonJs, AMD, ES6 modules, CSS, Images, JSON, Coffeescript, LESS, ... and your custom stuff.
JavaScript
64,061
star
2

webpack-dev-server

Serves a webpack app. Updates the browser on changes. Documentation https://webpack.js.org/configuration/dev-server/.
JavaScript
7,728
star
3

webpack-cli

Webpack's Command Line Interface
JavaScript
2,538
star
4

webpack-dev-middleware

A development middleware for webpack
JavaScript
2,468
star
5

react-starter

[OUTDATED] Starter template for React with webpack. Doesn't focus on simplicity! NOT FOR BEGINNERS!
JavaScript
2,215
star
6

webpack.js.org

Repository for webpack documentation and more!
MDX
2,197
star
7

docs

[OLD] documentation for webpack
JavaScript
1,456
star
8

enhanced-resolve

Offers an async require.resolve function. It's highly configurable.
JavaScript
897
star
9

memory-fs

[DEPRECATED use memfs instead] A simple in-memory filesystem. Holds data in a javascript object.
JavaScript
882
star
10

analyse

analyse web app for webpack stats
JavaScript
873
star
11

webpack-pwa

Example for a super simple PWA with webpack.
JavaScript
809
star
12

loader-utils

utils for webpack loaders
JavaScript
764
star
13

react-webpack-server-side-example

Example of an react application with webpack including server-side rendering.
JavaScript
460
star
14

node-libs-browser

[DEPRECATED] The node core libs for in browser usage.
JavaScript
445
star
15

watchpack

Wrapper library for directory and file watching.
JavaScript
373
star
16

webpack-with-common-libs

webpack with some common libraries
JavaScript
340
star
17

loader-runner

Runs (webpack) loaders
JavaScript
291
star
18

webpack-sources

Source code handling classes for webpack
JavaScript
254
star
19

changelog-v5

Temporary repo for the changelog for webpack 5
252
star
20

schema-utils

Options Validation
JavaScript
234
star
21

meeting-notes

Webpack core team meeting notes.
188
star
22

concord

[WIP] concord modules specification
156
star
23

example-app

[OUTDATED] example web app for webpack
JavaScript
139
star
24

fastparse

A very simple and stupid parser, based on a statemachine and regular expressions.
JavaScript
65
star
25

enhanced-require

[CURRENTLY UNMAINTAINED] Enhance the require function in node.js with support for loaders which preprocess files. This is a standalone polyfill for features of webpack.
JavaScript
64
star
26

playground

In-browser playground for webpack
JavaScript
59
star
27

analyse-tool

A tool to analyse your webpack build result. It allows to browse the compilation and points out options to optimize the build.
JavaScript
55
star
28

hot-node-example

Example for HMR in a node.js process
JavaScript
54
star
29

source-list-map

Fast line to line SourceMap generator.
JavaScript
39
star
30

benchmark

Run benchmarks for webpack.
JavaScript
37
star
31

core

[OBSOLETE in webpack 2] The core of webpack and enhanced-require...
JavaScript
26
star
32

media

23
star
33

voting-app

An application for casting votes on new webpack features and fixes.
JavaScript
22
star
34

tooling

A collection of reusable tooling for webpack repos.
JavaScript
20
star
35

graph

[DEPRECATED] Converts JSON stats from webpack to a nice SVG-Image.
JavaScript
13
star
36

template

[DEPRECATED] Create a new web app from a template.
JavaScript
10
star
37

webpack.github.com

webpack.github.com
JavaScript
10
star
38

management

Mission, Goals, projects and budget for webpack
6
star
39

github-org-overview

Scans all repos of a github organization and check if published
JavaScript
5
star
40

the-big-test

[OUTDATED] the big webpack/enhanced-require test
JavaScript
5
star
41

meetup-2018-05-08

QA for the webpack meetup in Munich
4
star
42

v4.webpack.js.org

Hosting for old version of webpack documentation
3
star
43

jquery-wpt-module

[DEPRECATED] webpack-template-module for jquery
JavaScript
2
star
44

bootstrap-wpt-module

[DEPRECATED] webpack-template-module for twitter's bootstrap
JavaScript
2
star
45

github-wiki

The server-side code (heruko) for serving the wiki as gh-pages.
JavaScript
2
star
46

enhanced-resolve-completion-demo

[OUTDATED] demo for the request completion of enhanced-resolve
JavaScript
2
star
47

webpack-tests-example

DEPRECATED (use mocha-loader now): A simple example for doing tests with webpack and mocha.
JavaScript
2
star