Movatterモバイル変換


[0]ホーム

URL:


webpack logo
ag grid
ag charts

Plugin API

Plugins are a key piece of the webpack ecosystem and provide the community witha powerful way to tap into webpack's compilation process. A plugin is able tohook into key events that are fired throughout each compilation. Every stepof the way, the plugin will have full access to thecompiler and, whenapplicable, the currentcompilation.

tip

For a high-level introduction to writing plugins, start withwriting a plugin.

Let's start by going overtapable utility, which provides the backbone ofwebpack's plugin interface.

Tapable

This small library is a core utility in webpack but can also be used elsewhereto provide a similar plugin interface. Many objects in webpack extend theTapable class. The class exposestap,tapAsync, andtapPromise methodswhich plugins can use to inject custom build steps that will be firedthroughout a compilation.

Please see thedocumentation to learnmore. An understanding of the threetap methods, as well as the hooks thatprovide them, is crucial. The objects that extendTapable (e.g. the compiler),the hooks they provide, and each hook's type (e.g. theSyncHook) will benoted.

Plugin Types

Depending on the hooks used andtap methods applied, plugins can function ina different number of ways. The way this works is closely related to thehooks provided byTapable. Thecompiler hooks each note the underlyingTapable hook indicating whichtap methods are available.

So depending on which event youtap into, the plugin may run differently. Forexample, when hooking into thecompile stage, only the synchronoustap methodcan be used:

compiler.hooks.compile.tap('MyPlugin',(params)=>{  console.log('Synchronously tapping the compile hook.');});

However, forrun which utilizes theAsyncHook, we can utilizetapAsyncortapPromise (as well astap):

compiler.hooks.run.tapAsync('MyPlugin',(source, target, routesList, callback)=>{    console.log('Asynchronously tapping the run hook.');callback();});compiler.hooks.run.tapPromise('MyPlugin',(source, target, routesList)=>{returnnewPromise((resolve)=>setTimeout(resolve,1000)).then(()=>{    console.log('Asynchronously tapping the run hook with a delay.');});});compiler.hooks.run.tapPromise('MyPlugin',async(source, target, routesList)=>{awaitnewPromise((resolve)=>setTimeout(resolve,1000));    console.log('Asynchronously tapping the run hook with a delay.');});

The moral of the story is that there are a variety of ways tohook into thecompiler, each one allowing your plugin to run as it sees fit.

Custom Hooks

In order to offer a custom hook to the compilation for other plugins totap into,you need to do the following:

  1. Create a module-scopeWeakMap for compilation hooks:

    const compilationHooks=newWeakMap<Compilation, MyHooks>();interfaceMyHooks{  custom: SyncHook<[number,string]>;}
  2. Create a static method on your plugin:

    staticgetCompilationHooks(compilation: Compilation): MyHooks{let hooks= compilationHooks.get(compilation);if(hooks===undefined){    compilationHooks.set(compilation, hooks={      custom:newSyncHook()});}return hooks;}
  3. Call hooks like below in your plugin:

    const hooks= MyPlugin.getCompilationHooks(compilation);hooks.custom.call(1,'hello');
  4. Other plugins can access your custom hooks too:

    import MyPluginfrom'my-plugin';const hooks= MyPlugin.getCompilationHooks(compilation);hooks.custom.tap('OtherPlugin',(n, s)=>{// magic});

Again, see thedocumentation fortapable to learn more about thedifferent hook classes and how they work.

Reporting Progress

Plugins can report progress viaProgressPlugin, which prints progress messages to stderr by default. In order to enable progress reporting, pass a--progress argument when running thewebpack CLI.

It is possible to customize the printed output by passing different arguments to thereportProgress function ofProgressPlugin.

To report progress, a plugin musttap into a hook using thecontext: true option:

compiler.hooks.emit.tapAsync({    name:'MyPlugin',    context:true,},(context, compiler, callback)=>{const reportProgress= context&& context.reportProgress;if(reportProgress)reportProgress(0.95,'Starting work');setTimeout(()=>{if(reportProgress)reportProgress(0.95,'Done work');callback();},1000);});

ThereportProgress function may be called with these arguments:

reportProgress(percentage,...args);
  • percentage: This argument is unused; instead,ProgressPlugin will calculate a percentage based on the current hook.
  • ...args: Any number of strings, which will be passed to theProgressPlugin handler to be reported to the user.

Note that only a subset of compiler and compilation hooks support thereportProgress function. SeeProgressPlugin for a full list.

Logging

Logging API is available since the release of webpack 4.37. Whenlogging is enabled instats configuration and/or wheninfrastructure logging is enabled, plugins may log messages which will be printed out in the respective logger format (stats, infrastructure).

  • Plugins should prefer to usecompilation.getLogger('PluginName') for logging. This kind of logging is stored in the Stats and formatted accordingly. It can be filtered and exported by the user.
  • Plugins may use thecompiler.getInfrastructureLogger('PluginName') for logging. Usinginfrastructure logging is not stored in the Stats and therefore not formatted. It's usually logged to the console/dashboard/GUI directly. It can be filtered by the user.
  • Plugins may use specific fallback logic for detecting logging supportcompilation.getLogger ? compilation.getLogger('PluginName') : console to provide a fallback for cases when an older webpack version is used which does not supportgetLogger method oncompilation object.

Next Steps

See thecompiler hooks section for a detailed listing of all the availablecompiler hooks and the parameters they make available.

8 Contributors

thelarkinnpksjcee-cloudbyzykEugeneHlushkowizardofhogwartssnitin315evenstensberg

[8]ページ先頭

©2009-2025 Movatter.jp