reactjs - 如何在 React 和 Webpack 项目中使用来自sharp模块的图像

标签 reactjs webpack sharp

这是一个 codesandbox我希望其中的图像由 sharp module 处理.我希望它这样做是因为我希望这个模块对我的 React 项目中的所有图像进行网络优化,并将它们转换为 webm。
这是相同的 codesandbox我尝试使用 ImageSharp 的地方

最佳答案

您将需要进行一些更改:
Webpack.config.js

  • 搬家 sharp-loaderrules :
  • 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/

    相关文章:

    javascript - Codepen 在预期很少的项目时返回空数组

    javascript - react : onClick on Mobile (iPhone) requires 2 taps?

    javascript - 在 Three.js 中从缓冲区(而不是路径)加载 STL

    javascript - Webpack 构建语法错误 : Unexpected token )

    node.js - NodeJs sharp Image library - Resize using Stream Api 抛出错误 'stream.push() after EOF'

    javascript - react :- It's not rendering my HTML

    javascript - 是否可以让 webpacks System.import 使用 ajax(用于进度事件)?

    node.js - 在webpack中选择正确的environment.ts

    node.js - 如何在可读的http流上运行Sharp转换并写入文件

    node.js - 如何使用sharp包压缩PNG文件?