面试题答案
一键面试获取编译上下文的方法
在Webpack自定义插件开发中,通过在插件的apply
方法中,接收compiler
对象来获取编译上下文。compiler
对象包含了Webpack整个生命周期的钩子,通过这些钩子可以访问到不同阶段的编译信息。例如:
class MyPlugin {
apply(compiler) {
compiler.hooks.compile.tap('MyPlugin', compilation => {
// compilation 就是编译上下文
});
}
}
常见用途
- 资源操作:可以访问和修改即将输出到最终bundle中的资源。比如修改CSS文件内容、对图片进行压缩处理等。
- 依赖分析:分析模块之间的依赖关系,对于一些特定的模块依赖可以进行特殊处理,例如将某些第三方库进行CDN引入等。
- 流程控制:在编译的不同阶段执行自定义逻辑,比如在编译开始前进行一些初始化操作,在编译结束后进行一些清理工作。
简单操作示例
以下示例展示了在编译结束后向输出的index.html
文件中插入一段自定义脚本:
class InsertScriptPlugin {
apply(compiler) {
compiler.hooks.emit.tapAsync('InsertScriptPlugin', (compilation, callback) => {
const htmlPath = 'index.html';
const html = compilation.assets[htmlPath].source();
const newHtml = html.toString().replace('</body>', `<script>console.log('This is a custom script inserted by plugin');</script></body>`);
compilation.assets[htmlPath] = {
source: function() {
return newHtml;
},
size: function() {
return newHtml.length;
}
};
callback();
});
}
}
module.exports = InsertScriptPlugin;
在Webpack配置中使用该插件:
const InsertScriptPlugin = require('./InsertScriptPlugin');
module.exports = {
// 其他配置
plugins: [
new InsertScriptPlugin()
]
};