You will need to make some changes:
Webpack.config.js
- Move
sharp-loader
to rules
:
const HtmlWebPackPlugin = require("html-webpack-plugin");
module.exports = {
module: {
rules: [
...
{
test: /\.(gif|jpe?g|png|svg|tiff)(\?.*)?$/,
loader: "sharp-loader",
query: {
name: "[name].[hash:8].[ext]",
cacheDirectory: true,
presets: {
// Preset 1
thumbnail: {
format: ["webp", "jpeg"],
width: 200,
quality: 60
},
// Preset 2
prefetch: {
// Format-specific options can be specified like this:
format: { id: "jpeg", quality: 30 },
mode: "cover",
blur: 100,
inline: true,
size: 50
}
}
}
}
]
},
devServer: {
...
},
plugins: [
...
]
};
If you are using Webpack 5:
Rule.query is deprecated in favor of Rule.options and
UseEntry.options.
Home.js
- The
sharp-loader
will transform logo into an array of one object because of this "outputs":[{"width": 500}]
. You will need to use the corresponding object:
import React from "react";
import logo from '../../react-logo.png?{"outputs":[{"width": 500}]}';
export default function Home() {
return (
<div>
<h2>Home</h2>
<img src={logo[0].url} />
</div>
);
}
If you are using require.context
it works the same way:
import React from "react";
function importAll(r) {
return r.keys().reduce((curr, key) => ((curr[key] = r(key)), curr), {});
}
const images = importAll(require.context('./images/?{"outputs":[{"width": 200}, {"width": 150}]}', true, /\.png$/));
export default function Home() {
return (
<div>
<h2>Home</h2>
<img src={images['./react-logo.png'][0].url} />
</div>
);
}
'../../react-logo.png?{"outputs":[{"width": 500}]}';
this is how sharp reads images from what I've read though – Folse