编写一个webpack plugin(基础篇)

作者 : 开心源码 本文共7963个字,预计阅读时间需要20分钟 发布时间: 2022-05-13 共279人阅读

编写一个webpack plugin(基础篇)

创立插件

webpack插件由以下组成

  • 一个具名javaScript函数
  • 在插件函数的 prototype 上定义一个 apply 方法。
  • 指定一个绑定到 webpack 自身的事件钩子。
  • 解决 webpack 内部实例的特定数据。
  • 功能完成后调用 webpack 提供的回调。
// 一个js具名函数function HelloWorldPlugin() {}//再函数的protoyupe上定义一个apply方法HelloWorldPlugin.prototype.apply = function (compiler) {    //指定一个挂载到webpack自身的事件钩子    compiler.hooks.emit.tapAsync(        'HelloWorldPlugin',        (compilation, callback) => {          console.log('This is an example plugin!');          console.log('Here’s the `compilation` object which represents a single build of assets:', compilation);            // 使用webpack提供的插件API操作构建          compilation.addModule(/* ... */);                  callback();        }      );}module.exports = HelloWorldPlugin;

Compiler 和 Compilation

  • compiler 对象代表了完整的 webpack 环境配置。这个对象在启动 webpack 时被一次性建立,并配置好所有可操作的设置,包括 options,loader 和 plugin。当在 webpack 环境中应用一个插件时,插件将收到此 compiler 对象的引用。可以使用它来访问 webpack 的主环境。

  • compilation 对象代表了一次资源版本构建。当运行 webpack 开发环境中间件时,每当检测到一个文件变化,就会创立一个新的 compilation,从而生成一组新的编译资源。一个 compilation 对象体现了当前的模块资源、编译生成资源、变化的文件、以及被跟踪依赖的状态信息。compilation 对象也提供了很多关键时机的回调,以供插件做自己设置解决时选择使用。

插件的不同类型

demo.png

  • Bail Hooks

    • 在这些 hooks 类型中,一个接一个地调用每个插件,并且 callback 会传入特定的 args。假如任何插件返回任何非 undefined 值,则由 hook 返回该值,并且不再继续调用插件 callback。许多有用的事件,如 optimizeChunks, optimizeChunkModules 都是 SyncBailHooks 类型。
  • Waterfall Hooks

    • 在这些 hooks 类型中,一个接一个地调用每个插件,并且会使用前一个插件的返回值,作为后一个插件的参数。必需考虑插件的执行顺序。 它必需接收来自先前执行插件的参数。第一个插件的值是 init。因而,waterfall hooks 必需提供至少一个参数。这种插件模式用于 Tapable 实例,而这些实例与 ModuleTemplate, ChunkTemplate 等 webpack 模板相互关联
  • Async Series Hook

    • 调用插件解决函数,传入所有参数,并使用签名 (err?: Error) -> void 调用回调函数。解决函数按照注册顺序进行调用。所有解决函数都被调用之后会调用 callback。 这种插件模式常用于 emit, run 等事件。
  • Async waterfall

    • 调用插件解决函数,传入当前值作为参数,并使用签名 (err?: Error) -> void 调用回调函数。在调用解决函数中的 nextValue,是下一个解决函数的当前值。第一个解决函数的当前值是 init。所有解决函数都被调用之后,会调用 callback,并且传入最后一个值。假如任何解决函数向 err 方法传递一个值,则会调用 callback,并且将这个错误传入,而后不再调用解决函数。 这种插件模式常用于 before-resolve, after-resolve 等事件。

Compiler 源码

Compilation 源码

tapAsync

在我们使用 tapAsync 方法 tap 插件时,我们需要调用 callback,此 callback 将作为最后一个参数传入函数。

class HelloAsyncPlugin {  apply(compiler) {    compiler.hooks.emit.tapAsync('HelloAsyncPlugin', (compilation, callback) => {      // 做少量异步的事情……      setTimeout(function() {        console.log('Done with async work...');        callback();      }, 1000);    });  }}module.exports = HelloAsyncPlugin;

tapPromise

在我们使用 tapPromise 方法 tap 插件时,我们需要返回一个 promise,此 promise 将在我们的异步任务完成时 resolve。

class HelloAsyncPlugin {  apply(compiler) {    compiler.hooks.emit.tapPromise('HelloAsyncPlugin', compilation => {      // 返回一个 Promise,在我们的异步任务完成时 resolve……      return new Promise((resolve, reject) => {        setTimeout(function() {          console.log('异步工作完成……');          resolve();        }, 1000);      });    });  }}module.exports = HelloAsyncPlugin;

过程

webpack在启动之后,读取到传入的配置参数,先初始化compiler对象并把配置参数注入到其中,

遍历配置文件中的plugin列表通过apply方法并将compiler对象传入。

这样我们即可以在插件实例的apply方法中通过compiler对象来监听webpack生命周期中广播出来的事件。

在事件中,我们也可以通过compiler对象来操作webpack的输出。

源码地址

官方demo

class FileListPlugin {  apply(compiler) {    // emit 是异步 hook,使用 tapAsync 触及它,还可以使用 tapPromise/tap(同步)    compiler.hooks.emit.tapAsync('FileListPlugin', (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;

灵魂拷问: 那么compilation里除了assets还有什么呢? 我们想要获取打包后的具体信息 例如:项目代码具体本分成多少个chunk,每个chunk下又有几个module 该怎样办?

官方另一个demo (血坑!!!!~!)

class MyPlugin {  apply(compiler) {    compiler.hooks.emit.tapAsync('MyPlugin', (compilation, callback) => {      // Explore each chunk (build output):      compilation.chunks.forEach(chunk => {        // Explore each module within the chunk (built inputs):        chunk.modules.forEach(module => {          // Explore each source file path that was included into the module:          module.fileDependencies.forEach(filepath => {            // we've learned a lot about the source structure now...          });        });        // Explore each asset filename generated by the chunk:        chunk.files.forEach(filename => {          // Get the asset source for each file generated by the chunk:          var source = compilation.assets[filename].source();        });      });      callback();    });  }}module.exports = MyPlugin;

心路历程

c ———–> Feel happy

o ———–> coding……

d ———–> Excuse me ?

i ———–> coding……

n ———–> Fuck!

g ———–> coding……

. ———–> Fuck~?

. ———–> coding……

. ———–> @!,#%.&(!.@#$%^^&()

(少儿不宜,请勿模仿)

错误起因: compilation.chunks === true; compilation.chunks.module === false;

compilation里有chunks,但是chunks里没有modules属性,只有 _modules. _modules里把module做了多种分类,无法获取有效信息

证据;

正确姿势:

compilation.getStats().toJson();// chunks = compilation.getStats().toJson().chunks;[ { id: 0,   //chunk id    rendered: true,    initial: false,    //require.ensure 产生的 chunk,非 initial    //initial 表示能否在页面初始化就需要加载的模块,而不是按需加载的模块    entry: false,    //能否含有 Webpack 的 runtime 环境,通过 CommonChunkPlugin 解决后,runtime 环境被提到最高层级的 chunk    recorded: undefined,    extraAsync: false,    size: 296855,    //chunk 大小、比特    names: [],    //require.ensure 不是通过 Webpack 配置的,所以 chunk 的 names 是空    files: [ '0.bundle.js' ],    //该 chunk 产生的输出文件,即输出到特定文件路径下的文件名称    hash: '42fbfbea594ba593e76a',    //chunk 的 hash,即 chunkHash    parents: [ 2 ],    //父级 chunk 的 id 值    origins: [ [Object] ]     //该 chunk 是如何产生的    },  { id: 1,    rendered: true,    initial: false,    entry: false,    recorded: undefined,    extraAsync: false,    size: 297181,    names: [],    files: [ '1.bundle.js' ],    hash: '456d05301e4adca16986',    parents: [ 2 ],    origins: [ [Object] ] }    ```     chunk -- origins  -- 形容了某一个 chunk 是如何产生的:     ```     {  "loc": "", // Lines of code that generated this chunk  "module": "(webpack)\\test\\browsertest\\lib\\index.web.js", // Path to the module  "moduleId": 0, // The ID of the module  "moduleIdentifier": "(webpack)\\test\\browsertest\\lib\\index.web.js", // Path to the module  "moduleName": "./lib/index.web.js", // Relative path to the module  "name": "main", // The name of the chunk  "reasons": [    // A list of the same `reasons` found in module objects  ]}//  assets = compilation.getStats().toJson().assets;[ {  "chunkNames": [],   // The chunks this asset contains  //这个输出资源包含的 chunks 名称。对于图片的 require 或者者 require.ensure 动态产生的 chunk 是不会有 chunkNames 的,但是在 entry 中配置的都是会有的  "chunks": [ 10, 6 ],   // The chunk IDs this asset contains   //这个输出资源包含的 chunk的ID。通过 require.ensure 产生的 chunk 或者者 entry 配置的文件都会有该 chunks 数组,require 图片不会有  "emitted": true,   // Indicates whether or not the asset made it to the `output` directory   //使用这个属性标识 assets 能否应该输出到 output 文件夹  "name": "10.web.js",   // The `output` filename  //表示输出的文件名  "size": 1058 ,  // The size of the file in bytes  //输出的这个资源的文件大小  modules: []  // 该chunk下包含的module}  { name: '1.bundle.js',    size: 299469,    chunks: [ 1, 3 ],    chunkNames: [],    emitted: undefined,    isOverSizeLimit: undefined },  { name: 'bundle.js',        size: 968,        chunks: [ 2, 3 ],        chunkNames: [ 'main' ],        emitted: undefined,        isOverSizeLimit: undefined },  { name: 'vendor.bundle.js',    size: 5562,    chunks: [ 3 ],    chunkNames: [ 'vendor' ],    emitted: undefined,    isOverSizeLimit: undefined }]//  modules = compilation.getStats().toJson().modules;{ id: 10,//该模块的 id 和 `module.id` 一样identifier: 'C:\\Users\\Administrator\\Desktop\\webpack-chunkfilename\\node_odules\\html-loader\\index.js!C:\\Users\\Administrator\\Desktop\\webpack-chunkflename\\src\\Components\\Header.html',//Webpack 内部使用这个唯一的 ID 来表示这个模块name: './src/Components/Header.html',//模块名称,已经转化为相对于根目录的路径index: 10,index2: 8,size: 62,cacheable: true,//表示这个模块能否可以缓存,调用 this.cacheable()built: true,//表示这个模块通过 Loader、Parsing、Code Generation 阶段optional: false,//所以对该模块的加载一律通过 try..catch 包裹prefetched: false,//表示该模块能否是预加载的。即在第一个 import、require 调用之前就开始解析和打包该模块https://webpack.js.org/plugins/prefetch-plugin/chunks: [ 0 ],//该模块在那个 chunk 中出现assets: [],//该模块包含的所有的资源文件集合issuer: 'C:\\Users\\Administrator\\Desktop\\webpack-chunkfilename\\node_modues\\eslint-loader\\index.js!C:\\Users\\Administrator\\Desktop\\webpack-chunkfilname\\src\\Components\\Header.js',//是谁开始本模块的调用的,即模块调用发起者issuerId: 1,//发起者的 moduleidissuerName: './src/Components/Header.js',//发起者相对于根目录的路径profile: undefined,failed: false,//在解析或者者解决该模块的时候能否失败errors: 0,//在解析或者者解决该模块的能否出现的错误数量warnings: 0,//在解析或者者解决该模块的能否出现的警告数量reasons: [ [Object] ],usedExports: [ 'default' ],providedExports: null,depth: 2,source: 'module.exports = "<header class=\\"header\\">{{text}}</header>";' }//source 是模块内容,但是已经变成了字符串了

通过广播自己设置事件来实现组件之间相互通讯

自己设置webpack事件流大概分为4步:

  • 引入Tapable并找到你想用的hook,(同步hook or 异步hook)
const { SyncHook } = require("tapable");
  • 实例化Tapable中你所需要的hook并挂载在compiler或者compilation上
compiler.hooks.myHook = new SyncHook(['data'])
  • 在你所需要广播事件的时机执行call方法并传入数据
compiler.hooks.environment.tap(pluginName, () => {       //广播自己设置事件       compiler.hooks.myHook.call("It's my plugin.")});
  • 在你需要监听事件的位置tap监听
compiler.hooks.myHook.tap('Listen4Myplugin', (data) => {    console.log('@Listen4Myplugin', data)})

本文只对webpack plugin做基础入门级的详情, 具体细节以及api变动以官方文档或者github为准

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » 编写一个webpack plugin(基础篇)

发表回复