Writing a plugin

Webpack engine plugin provides the ability to complete third-party developers. Build callback, development can use the staged introduction of their own behavior to webpack build process. Create a plug-in to create more advanced than the loader, because you will need to understand the internal characteristics of some of the underlying webpack to do the appropriate hooks, so be prepared to read some source!

Create plug-ins

webpack Plug consists of:

  • A JavaScript function named.
  • Definition of a prototype plug-in function  apply method.
  • Specify a bind itself to webpack event hook .
  • Examples of specific internal data processing webpack.
  • Webpack calls the callback function provided after completion.
// 一个 JavaScript 命名函数。
function MyExampleWebpackPlugin() { }; // 在插件函数的 prototype 上定义一个 `apply` 方法。 MyExampleWebpackPlugin.prototype.apply = function(compiler) { // 指定一个挂载到 webpack 自身的事件钩子。 compiler.plugin('webpacksEventHook', function(compilation /* 处理 webpack 内部实例的特定数据。*/, callback) { console.log("This is an example plugin!!!"); // 功能完成后调用 webpack 提供的回调。 callback(); }); }; 

Compiler 和 Compilation

The two most important resource is in plug-in development  compiler and  compilation objects. Understand their role is an extension of an important first step webpack engine.

  • compiler Object represents a complete webpack environment configuration. The object is to establish a one-time startup webpack, and configure all operational settings, including options, loader and plugin. When a plug-in application webpack environment, plug-in will receive a reference to this compiler object. You can use it to access the main environmental webpack.

  • compilation Object represents a version construction resources. When running webpack middleware development environment, to detect whenever a file changes, it will create a new compilation, so as to generate a new set of compiled resources. A compilation target performance of the current resource module, compiled resources, change the file, and tracked dependent status information. compilation object also provides a number of key timing correction, choose to use when doing a custom plug-ins for processing.

These two components are an integral part of any webpack plug-in (in particular  compilation), so developers read the source code, and then they are familiar with, feel benefit:

The basic plug-in architecture

Plug-ins are from "having a  apply method prototype object" instantiated out. This  apply method of installing the plug, will be called once webpack compiler. apply The method WebPACK compiler may receive a reference to the object so that the object can be accessed in the callback function compiler. A simple plug-in is structured as follows:

function HelloWorldPlugin(options) { // 使用 options 设置插件实例…… } HelloWorldPlugin.prototype.apply = function(compiler) { compiler.plugin('done', function() { console.log('Hello World!'); }); }; module.exports = HelloWorldPlugin; 

Then, to install this plugin, you only need to configure the webpack  plugin add an instance array:

var HelloWorldPlugin = require('hello-world'); var webpackConfig = { // ... 这里是其他配置 ... plugins: [ new HelloWorldPlugin({options: true}) ] }; 

Access compilation objects

When using the compiler object, you can bind a callback function provides a compilation compilation of references, and then get each new compilation object. These objects provide a compilation of some hook function to be hooked into a number of steps in the build process.

function HelloCompilationPlugin(options) {} HelloCompilationPlugin.prototype.apply = function(compiler) { // 设置回调来访问 compilation 对象: compiler.plugin("compilation", function(compilation) { // 现在,设置回调来访问 compilation 中的步骤: compilation.plugin("optimize", function() { console.log("Assets are being optimized."); }); }); }; module.exports = HelloCompilationPlugin; 

About  compilercompilation callbacks, and more information is available other important objects, see the  plug-in  documentation.

Asynchronous compiler plugin

There are a number of steps to compile plug-in is asynchronous, which will require additional pass a callback callback function, and at the end of the plug-run, _ must be _ callback function is invoked.

function HelloAsyncPlugin(options) {} HelloAsyncPlugin.prototype.apply = function(compiler) { compiler.plugin("emit", function(compilation, callback) { // 做一些异步处理…… setTimeout(function() { console.log("Done with async work..."); callback(); }, 1000); }); }; module.exports = HelloAsyncPlugin; 

Examples

Once we are able to deeply understand webpack compiler and each individual compilation, we rely webpack engine will have an infinite number of things you can do. We can reformat existing documents, create derivative files, or create a brand new generation file.

Let's write a simple example plug-in, called to generate  filelist.md a new file; the file content is to build a list of all the generated files. This plug-in is probably something like this:

function FileListPlugin(options) {} FileListPlugin.prototype.apply = function(compiler) { compiler.plugin('emit', function(compilation, callback) { // 在生成文件中,创建一个头部字符串: var filelist = 'In this build:\n\n'; // 遍历所有编译过的资源文件, // 对于每个文件名称,都添加一行内容。 for (var filename in compilation.assets) { filelist += ('- '+ filename +'\n'); } // 将这个列表作为一个新的文件资源,插入到 webpack 构建中: compilation.assets['filelist.md'] = { source: function() { return filelist; }, size: function() { return filelist.length; } }; callback(); }); }; module.exports = FileListPlugin; 

Different types of plug-ins

webpack plug-ins can be divided into different types according to the event that it is registered. Each event hook decide how it registered the application plug-ins.

  • Synchronous (synchronous) will be used when Tapable example application plug-ins:

applyPlugins(name: string, args: any...)

applyPluginsBailResult(name: string, args: any...)

This means that each widget callbacks, will be a particular  args one by one call. This is the most basic form of plug-ins. Many useful events (for example  "compile""this-compilation"), is expected to plug-in synchronous execution.

  • Waterfall flows may use when (waterfall) plug-in applications:

applyPluginsWaterfall(name: string, init: any, args: any...)

This type of plug-in after each turn call other plug-ins called before a plug-in return of a call, as the argument to a plug. Such plug-in execution order must be considered. After a plug-in must wait before execution, in order to receive parameters. Value of the first plug-in is 初始值(init). This mode is used with  webpack the relevant template Tapable example (e.g.  ModuleTemplateChunkTemplate etc.).

  • 异步(asynchronous) When all the plugins are applied asynchronously using

applyPluginsAsync(name: string, args: any..., callback: (err?: Error) -> void)

This type of plug-in processing function when called, will pass all parameters and a signature for the  (err?: Error) -> void callback function. Handler calls upon the order of registration. After calling all the handlers will be called  callback. It is also  "emit""run" and other common mode events.

  • Asynchronous waterfall (async waterfall) plug-in will Falls asynchronous applications.

applyPluginsAsyncWaterfall(name: string, init: any, callback: (err: Error, result: any) -> void)

This type of plug-in processing function when called, will pass the current value (current value) and with a signature for the  (err: Error, nextValue: any) -> void. callback function. When the call  nextValue is the current value (current value) to the next handler, the current value of the first handler is  init. After completion of all call processing functions, it will call the callback, and the last incoming value. If any handler pass a  err value, this callback is invoked and this error object passed, and no other call processing functions. This mode is useful for the plug-like  "before-resolve" , and  "after-resolve" events like this.

  • Asynchronous serial (async series) which is the same asynchronous (asynchronous), but if any plug-in registration fails, instead of calling other plug-ins.

applyPluginsAsyncSeries(name: string, args: any..., callback: (err: Error, result: any) -> void)

- Parallel (Parallel) -

applyPluginsParallel(name: string, args: any..., callback: (err?: Error) -> void)

applyPluginsParallelBailResult(name: string, args: any..., callback: (err: Error, result: any) -> void)

Guess you like

Origin www.cnblogs.com/cangqinglang/p/11266240.html