@bornkiller
2017-07-21T17:09:26.000000Z
字数 2122
阅读 1707
webpack
webpack
作为前端开发利器,提供Plugin
,Loader
扩展机制。开发者可以充分利用Webpack
插件机制,扩展需要的功能。Loader
功能简单,实现容易,不做说明。
插件的结构固定,代码如下:
class CompressionPlugin {
constructor(options) {
this.options = _.assign({}, defaultOption, options);
}
apply(compiler) {
compiler.plugin('compilation', (compilation) => {
// Just boilerplate code
compilation.plugin('module-asset', (module, file) => {
noop(file);
});
});
compiler.plugin('emit', (compilation, callback) => {
const assets = compilation.assets;
}
}
}
开发插件包含以下几步:
ES6 class
)apply
函数webpack lifecycle hook
webpack compiler, compilation
对象插件的核心简而概之:正确的时间做正确的事。
webpack hook
数量繁多,参考官方文档。第三方插件功能多集中在文件处理,典型案例html-webpack-plugin,笔者也将实现简单插件,实现自动清理非本次编译生成文件。
class CleanupPlugin {
constructor(options) {
this.options = _.assign({}, defaultCleanupOptions, options);
this.rules = this.options.exclude;
const status = validateExcludeRules(this.rules);
if (!status) {
throw new Error('CleanupPlugin exclude array must consist of string or RegExp');
}
this.exclusion = matchExcludeRules(this.rules);
}
apply(compiler) {
compiler.plugin('after-emit', (compilation, callback) => {
const assets = Reflect.ownKeys(compilation.assets);
const files = recursiveReadDir(compiler.options.output.path);
const extraneous = files.filter((filename) => !assets.includes(filename)).filter((filename) => !this.exclusion(filename));
extraneous.forEach((filename) => {
fs.unlinkSync(path.resolve(compiler.options.output.path, filename));
if (!this.options.quite) {
// eslint-disable-next-line no-console
console.log(`${filename} already deleted`);
}
});
callback();
});
}
}
compilation.assets
表示webpack compilation
生成文件,读取输出目录文件,交叉比对,就能得到冗余文件并清理。完整代码见https://github.com/bornkiller/webpack-plugin-strawberry。
笔者学习开发插件的过程,翻阅部分插件,挂载lifecycle hook
如下:
optimize-chunk-asset
- prepack-webpack-pluginemit
- webpack-manifest-plugindone
- webpack-cleanup-pluginwebpack hook
挂载执行方式不同,存在以下几种:
applyPlugins
- 同步并行applyPluginsBailResult
- 同步串行,当handler
非空返回值,调用终止,并返回结果applyPluginsWaterfall
- 同步串行,前置handler
返回值作为后置handler
输入参数applyPluginsAsync === applyPluginsAsyncSeries
- 异步串行applyPluginsAsyncSeriesBailResult
- 异步串行,当handler callback
包含响应值,则执行回调,调用终止applyPluginsAsyncWaterfall
- 异步串行,前置handler callback
响应值作为后置handler
输入参数Email: hjj491229492@hotmail.com