title: webpack plugins Hooks 介绍
img: //bloglibs.oss-cn-beijing.aliyuncs.com/techlogo/nodejs-logo.png
date: 2018-07-16 23:25:54
tags:
- webpack
- hooks
- compiler
category: - – 技术
webpack 使用有一段时间了, 有时候为了工程化比较完善,不得不自己开发添加一些hooks完善脚手架,
使用
pluginsConfig.push(new FinishShell({
onBuildEnd: ['zip -r sdk_'+appVersions+'.zip ./'+publishDirName]
}))
plugins
'use strict';
var exec = require('child_process').exec;
function puts(error, stdout, stderr) {
console.log(stdout);
}
function WebpackShellPlugin(options) {
var defaultOptions = {
onBuildStart: [],
onBuildEnd: []
};
this.options = Object.assign(defaultOptions, options);
}
WebpackShellPlugin.prototype.apply = function(compiler) {
const options = this.options;
compiler.plugin("compilation", compilation => {
if(options.onBuildStart.length){
console.log("Executing pre-build scripts");
options.onBuildStart.forEach(script => exec(script, puts));
}
});
compiler.plugin('done', function(){
if(options.onBuildEnd.length){
console.log("Executing post-build scripts");
options.onBuildEnd.forEach(script => exec(script, puts));
}
})
};
module.exports = WebpackShellPlugin;
重要的声明周期
- -> 传入options并校验
- -> 创建全局唯一生命流程compiler对象
- -> 调用options.plugins数组插件函数
- -> 执行compiler.run真正跑程序
- -> new 构建的Compilation
- -> 通知addEntry钩子加载entry的资源
- -> compilation进行buildModule
- -> compilation进行shouldGenerateChunkAssets
- -> compilation.emit完成