webpack插件实现依赖动态注入
const CommonJsRequireDependency = require('webpack/lib/dependencies/CommonJsRequireDependency');
let sets = new Set();
compiler.plugin('compilation', compilation => {
compilation.plugin('buildModule', module => {
let filepath = module.context;
if (!sets.has(filepath)) {
sets.add(filepath);
// 内容
if (fs.existsSync(injectFilePath)) {
//绝对路径下存在就加入
module.dependencies.push(
new CommonJsRequireDependency(injectFilePath)
);
}
}
});
});插件实现在入口文件内无需引用对应的依赖,在webpack plugin生命周期内判断文件是否存在进行注入。
CommonJsRequireDependency的功能是对输入的文件地址解析成插件可读的数据
最后更新于
这有帮助吗?