我看到了NormalModuleReplacementPlugin(source code),并希望对图像密码集执行相同的操作。
我以如下方式导入图像:import image from './image.jpg'
,但也想处理@ 2x和@ 3x图像而不必显式地导入它们(就像Metro Bundler / React Native一样)。
我有这个伪Webpack插件:
const path = require('path');
const getSrcSet = (string, number) => string.split('.').join(`@${number}x.`);
class SrcSetPlugin {
apply(compiler) {
const resourceRegExp = /\.jpe?g|png$/i;
compiler.hooks.normalModuleFactory.tap('SrcSetPlugin', (nmf) => {
nmf.hooks.beforeResolve.tap('SrcSetPlugin', (result) => {
if (!result) return;
if (resourceRegExp.test(result.request)) {
// pseudo-code to also import other srcSets
result.request2 = getSrcSet(result.request, 2);
result.request3 = getSrcSet(result.request, 3);
}
return result;
});
nmf.hooks.afterResolve.tap('SrcSetPlugin', (result) => {
if (!result) return;
if (resourceRegExp.test(result.resource)) {
console.log(result);
process.exit(0);
// pseudo-code to also resolve other srcSets
result.resource2 = path.resolve(
path.dirname(result.resource),
getSrcSet(result.resource.split('/').slice(-1), 2),
);
result.resource3 = path.resolve(
path.dirname(result.resource),
getSrcSet(result.resource.split('/').slice(-1), 3),
);
}
return result;
});
});
}
}
module.exports = SrcSetPlugin;
是否可以告诉Webpack为一个userRequest处理多个文件?
预先感谢
编辑:
输入
import image from './image.jpg';
输出
console.log(image);
> { 1x: '/images/image.jpg', 2x: '/images/image@2x.jpg', 3x: '/images/image@3x.jpg' }