编写一个webpack plugin(基础篇)

编写一个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-chunkf
lename\\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_modu
es\\eslint-loader\\index.js!C:\\Users\\Administrator\\Desktop\\webpack-chunkfil
name\\src\\Components\\Header.js',
//是谁开始本模块的调用的,即模块调用发起者
issuerId: 1,
//发起者的 moduleid
issuerName: './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为准

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容