I’m working on a React project using Craco to manage Webpack configurations. My goal is to use WebP images for better performance, falling back to PNGs if WebP is not supported. I’ve already converted all my images to WebP and placed them in the same directories as the original PNGs.
However, when I run npm run build
, the WebP images are not being included in the build/static/media folder, while the PNGs are.
Here’s a summary of my configurations:
craco.config.js
const path = require("path");
module.exports = {
webpack: {
alias: {
"@components": path.resolve(__dirname, "src/components/"),
"@context": path.resolve(__dirname, "src/context/"),
"@assets": path.resolve(__dirname, "src/assets/"),
"@utils": path.resolve(__dirname, "src/utils/"),
"@data": path.resolve(__dirname, "src/data/"),
},
configure: (webpackConfig) => {
console.log("Adding file-loader for WebP");
const oneOfRule = webpackConfig.module.rules.find((rule) => rule.oneOf);
if (oneOfRule) {
console.log("Rule before modification:", oneOfRule.oneOf.map(rule => rule.test));
oneOfRule.oneOf.unshift({
test: /.(png|jpg|jpeg|webp)$/i,
use: [
{
loader: require.resolve("file-loader"),
options: {
name: "static/media/[name].[hash:8].[ext]",
},
},
],
});
console.log("WebP loader applied for: /\.(png|jpg|jpeg|webp)$/i");
console.log("Rule after modification:", oneOfRule.oneOf.map(rule => rule.test));
}
return webpackConfig;
},
},
};
As you can see I added a few logs in the config to show the rules before and after modification. The logs show that the WebP loader is being applied, but the WebP files are still not included in the build.
Adding file-loader for WebP
Rule before modification: [
[ /.avif$/ ],
[ /.bmp$/, /.gif$/, /.jpe?g$/, /.png$/ ],
/.svg$/,
/.(js|mjs|jsx|ts|tsx)$/,
/.(js|mjs)$/,
/.css$/,
/.module.css$/,
/.(scss|sass)$/,
/.module.(scss|sass)$/,
undefined
]
WebP loader applied for: /\.(png|jpg|jpeg|webp)$/i
Rule after modification: [
/.(png|jpg|jpeg|webp)$/i,
[ /.avif$/ ],
[ /.bmp$/, /.gif$/, /.jpe?g$/, /.png$/ ],
/.svg$/,
/.(js|mjs|jsx|ts|tsx)$/,
/.(js|mjs)$/,
/.css$/,
/.module.css$/,
/.(scss|sass)$/,
/.module.(scss|sass)$/,
undefined
]