这是一个 codesandbox我希望其中的图像由 sharp module 处理.我希望它这样做是因为我希望这个模块对我的 React 项目中的所有图像进行网络优化,并将它们转换为 webm。
这是相同的 codesandbox我尝试使用 ImageSharp 的地方
最佳答案
您将需要进行一些更改:
Webpack.config.js
sharp-loader
至 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: [
...
]
};
如果您正在使用 Webpack 5 :Rule.query is deprecated in favor of Rule.options and UseEntry.options.
Home.js
sharp-loader
因为这个"outputs":[{"width": 500}]
将标志转换成一个对象的数组.您将需要使用相应的对象: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>
);
}
如果您正在使用 require.context
它的工作方式相同:
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>
);
}
关于reactjs - 如何在 React 和 Webpack 项目中使用来自sharp模块的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67476896/