[译]如何写一个webpack插件

原文:how to write a pluginjavascript

译者:neal1991java

welcome to star my articles-translator , providing you advanced articles translation. Any suggestion, please issue or contact mewebpack

LICENSE: MITgit

插件可以将webpack引擎的所有潜力暴露给第三方的开发者。经过使用阶段构建回调,开发者可以将他们本身的行为引入到webpack的构建过程当中。构建插件比构建loader更高级,由于你须要理解一些webpack低层次的内部钩子。准备好阅读一些源代码吧!github

Compiler以及Compilation

在开发插件的时候最重要的两个资源就是compilercompilation对象。理解它们的角色是拓展webpack引擎重要的第一步。web

  • compiler对象表明了完整的配置的webpack环境。一旦开启webpack以后,这个对象就被构建了,而且这个对象会使用全部操做设置,包括options, loaders, 以及plugins来进行配置。当将一个插件应用到webpack环境中,这个插件将会得到一个对于这个compiler的引用。使用这个compiler能够访问主要的webpack环境。数组

  • 一个compilation对象表明版本资源的一次构建。当运行webpack开发中间件的时候,每次检测到文件变化的时候都会产生一个新的compilation,所以会生成一系列编译后的资源。Compilation表示有关模块资源,已编译资源,已更改文件和监视依赖关系的当前状态的信息。该compilation还提供了许多回调点,插件能够选择执行自定义操做。架构

这两个组件是任何webpack插件(特别是compilation)的内部一部分,所以开发者熟悉这些源代码文件以后将会受益非凡:app

基本的插件架构

插件是实例对象,而且在它们的prototype上,会有一个apply方法。当安装这个插件的时候,这个apply方法就会被webpack compiler调用。这个apply会给出一个对于潜在的webpack compiler的引用,保证了对于compiler回调的访问。一个简单的插件结构以下:

function HelloWorldPlugin(options) {
  // Setup the plugin instance with options...
}

HelloWorldPlugin.prototype.apply = function(compiler) {
  compiler.plugin('done', function() {
    console.log('Hello World!'); 
  });
};

module.exports = HelloWorldPlugin;

接着是安装这个插件,只要在你的webpack 配置plugins数组里面添加一个实例:

var HelloWorldPlugin = require('hello-world');

var webpackConfig = {
  // ... config settings here ...
  plugins: [
    new HelloWorldPlugin({options: true})
  ]
};

访问compilation

使用compiler对象,你可能绑定提供那个对于每个新的compilation引用的回调。这些compilation提供对于在构建过程当中对于不少步骤钩子的回调。

function HelloCompilationPlugin(options) {}

HelloCompilationPlugin.prototype.apply = function(compiler) {

  // Setup callback for accessing a compilation:
  compiler.plugin("compilation", function(compilation) {
    
    // Now setup callbacks for accessing compilation steps:
    compilation.plugin("optimize", function() {
      console.log("Assets are being optimized.");
    });
  });
};

module.exports = HelloCompilationPlugin;

对于更多关于compiler以及compilation上的回调以及其余重要的对象,请参考 [[plugins API|plugins]] 文档。

异步compilation plugins

有一些compilation插件步骤是异步的,而且当你的插件完成运行的时候,传递一个必须被调用的回调函数。

function HelloAsyncPlugin(options) {}

HelloAsyncPlugin.prototype.apply = function(compiler) {
  compiler.plugin("emit", function(compilation, callback) {

    // Do something async...
    setTimeout(function() {
      console.log("Done with async work...");
      callback();
    }, 1000);

  });
};

module.exports = HelloAsyncPlugin;

一个简单的例子

一旦咱们能够锁定到webpack compiler以及每个独立的compilation,咱们能够利用引擎自己就能发挥无穷的潜力。咱们可以从新格式化存在的文件,建立衍生文件,或者制造全新的资源。

让咱们写一个简单的可以生成一个新的打包文件filelist.md的插件例子;这个文件的内容会列出全部存在咱们build以内的资源文件。这个插件可能看起来是这个样子的:

function FileListPlugin(options) {}

FileListPlugin.prototype.apply = function(compiler) {
  compiler.plugin('emit', function(compilation, callback) {
    // Create a header string for the generated file:
    var filelist = 'In this build:\n\n';

    // Loop through all compiled assets,
    // adding a new line item for each filename.
    for (var filename in compilation.assets) {
      filelist += ('- '+ filename +'\n');
    }
    
    // Insert this list into the Webpack build as a new file asset:
    compilation.assets['filelist.md'] = {
      source: function() {
        return filelist;
      },
      size: function() {
        return filelist.length;
      }
    };

    callback();
  });
};

module.exports = FileListPlugin;

有用的插件模式

插件容许在webpack构建系统内发挥无尽量的定制化。这容许你建立自定义的资源类型,执行特殊的构建调整,或者设置在使用中间件的时候进一步提高webpack运行时间。下面的webpack的一些特性在开发插件的时候变得颇有用。

探索assets, chunks, modules, 以及dependencies

在compilation完成以后,compilation中的全部的结构均可能被遍历。

function MyPlugin() {}

MyPlugin.prototype.apply = function(compiler) {
  compiler.plugin('emit', function(compilation, callback) {
    
    // Explore each chunk (build output):
    compilation.chunks.forEach(function(chunk) {
      // Explore each module within the chunk (built inputs):
      chunk.modules.forEach(function(module) {
        // Explore each source file path that was included into the module:
        module.fileDependencies.forEach(function(filepath) {
          // we've learned a lot about the source structure now...
        });
      });

      // Explore each asset filename generated by the chunk:
      chunk.files.forEach(function(filename) {
        // Get the asset source for each file generated by the chunk:
        var source = compilation.assets[filename].source();
      });
    });

    callback();
  });
};

module.exports = MyPlugin;
  • compilation.modules: 在compilation中由模块(构建输入)组成的数组。每一个模块管理来自于源代码库中的源文件的构建。

  • module.fileDependencies: 包含在模块中的源文件路径数组。 这包括源JavaScript文件自己(例如:index.js)以及所需的全部依赖项资源文件(样式表,图像等)。 查看依赖关系对于查看哪些源文件属于模块颇有用。

  • compilation.chunks: Compilation中由chunks组成的数组(构建输出)。 每一个chunk管理最终渲染资源的组合。

  • chunk.modules: 包含在一个chunk中的模块数组。 经过扩展,您能够查看每一个模块的依赖关系,以查看传递到chunk中的原始源文件

  • chunk.files: 由chunk生成的输出文件名的数组。 您能够从compilation.assets表访问这些资源。

检测观察图

在运行webpack中间件时,每一个compilation都包含一个fileDependencies数组(正在监视的文件)和一个将观察文件路径映射到时间戳的fileTimestamps哈希。 这些对于检测compilation中哪些文件已更改很是有用:

function MyPlugin() {
  this.startTime = Date.now();
  this.prevTimestamps = {};
}

MyPlugin.prototype.apply = function(compiler) {
  compiler.plugin('emit', function(compilation, callback) {
    
    var changedFiles = Object.keys(compilation.fileTimestamps).filter(function(watchfile) {
      return (this.prevTimestamps[watchfile] || this.startTime) < (compilation.fileTimestamps[watchfile] || Infinity);
    }.bind(this));
    
    this.prevTimestamps = compilation.fileTimestamps;
    callback();
  }.bind(this));
};

module.exports = MyPlugin;

您还能够将新的文件路径传入观察图,以便在这些文件更改时接收compilation触发器。 只需将有效的文件路径推送到compilation.fileDependencies数组中便可将其添加到观察列表中。 注意:在每一个compilation中重建fileDependencies数组,所以您的插件必须将本身观察的依赖项推送到每一个编译中,以使它们保持监视。

改变的chunks

与观察图相似,经过跟踪它们的哈希值,能够在compilation中监视更改的块(或模块)。

function MyPlugin() {
  this.chunkVersions = {};
}

MyPlugin.prototype.apply = function(compiler) {
  compiler.plugin('emit', function(compilation, callback) {
    
    var changedChunks = compilation.chunks.filter(function(chunk) {
      var oldVersion = this.chunkVersions[chunk.name];
      this.chunkVersions[chunk.name] = chunk.hash;
      return chunk.hash !== oldVersion;
    }.bind(this));
    
    callback();
  }.bind(this));
};

module.exports = MyPlugin;
相关文章
相关标签/搜索