webpack初识之插件
编写webpack插件比编写loader更加复杂,插件会接触到webpack内部底层接口。实现插件主要是在原型链上实现apply方法。webpack在实例化时,会调用所有插件的apply方法。通过在apply方法内,监听webpack的Event Hooks(事件钩子),webpack在编译时,根据其编译阶段触发对应的钩子函数。如:
function MyPlugin (options) {} MyPlugin.prototype.apply = function (compiler) { compiler.plugin('done', function (compilation, callback) { console.log('done'); // console.log(compilation); }); compiler.plugin('compilation', function () { console.log('compilation'); }); compiler.plugin('emit', function (compilation, callback) { console.log('emit'); let content = '测试创建文件'; compilation.assets['test.md'] = { source: function () { return content; }, size: function () { return content.length; } }; console.log(compilation); callback(); }); };
名词解释:
compiler :
webpack的配置信息和api接口(主要是compiler.plugin)--- 详情见官方文档
compilation:
每个Event Hooks(事件钩子)对应的编译进程,callback相当于express中间件的next方法,存在于异步Event Hooks中 --- 详情见官方文档