【问题标题】:How to load SVG images in next.js using file-loader?如何使用文件加载器在 next.js 中加载 SVG 图像?
【发布时间】:2020-10-12 00:13:19
【问题描述】:

我添加了如下加载配置:

config.module.rules.unshift({
  test: /\.svg$/,
  use: {
    loader: 'file-loader',
    options: {
      esModule: false,
      name: '[name]-[hash].[ext]',
      outputPath: 'static/images',
    },
  },
});

这确实会生成预期的文件:

❯ ls -l .next/static/images/*-*.svg
-rw-r--r--  1 gajus  staff  2755 Oct 11 19:05 .next/static/images/BAGEL-c8eb9c0fab3c81a8ce2ca37b91e45447.svg
-rw-r--r--  1 gajus  staff  1399 Oct 11 19:05 .next/static/images/CARROT-6f210c93ab8a1dffb7613368a5cbb5fe.svg
-rw-r--r--  1 gajus  staff  1223 Oct 11 19:05 .next/static/images/CHOCOLATE_BAR-26d9835f780bee61f42a772bcc4b0358.svg
-rw-r--r--  1 gajus  staff  1643 Oct 11 19:05 .next/static/images/COOKIE-dc51bfc82c7bec0bc39a79de154027d2.svg
-rw-r--r--  1 gajus  staff  1779 Oct 11 19:05 .next/static/images/CROISSANT-fbbd24736806af790ed7b7eff9c29ce5.svg
-rw-r--r--  1 gajus  staff  4255 Oct 11 19:05 .next/static/images/DOUGHNUT-9cd981749f95b790e0c14fdd24189117.svg
-rw-r--r--  1 gajus  staff  1275 Oct 11 19:05 .next/static/images/MANGO-6318f4f9015e40d8d2177b299afc7563.svg
-rw-r--r--  1 gajus  staff   639 Oct 11 19:05 .next/static/images/RED_APPLE-9ad3d18099978a24a614c5f58a8d198b.svg
-rw-r--r--  1 gajus  staff  1975 Oct 11 19:05 .next/static/images/SHORTCAKE-cb1521d4a45c8e4b808d6309fbc4690c.svg

但是,实际的图像包含 base64 编码的内容,例如

cat .next/static/images/BAGEL-c8eb9c0fab3c81a8ce2ca37b91e45447.svg | head -c 100
export default "data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMzYgMzYiIHhtbG5zPSJodHRwOi8vd3d3L

【问题讨论】:

    标签: webpack next.js


    【解决方案1】:

    这并不是我想要的,但我设法简单地禁用了url-loader

    const imageRule = config.module.rules.find((rule) => {
      return String(rule.test) === String(/\.(jpe?g|png|svg|gif)$/i);
    });
    
    if (!imageRule) {
      throw new Error('Unexpected state');
    }
    
    const fallback = imageRule.oneOf[imageRule.oneOf.length - 1];
    
    if (fallback.resourceQuery) {
      throw new Error('Unexpected state');
    }
    
    const urlLoader = fallback.use[0];
    
    if (urlLoader.loader !== 'url-loader') {
      throw new Error('Unexpected state');
    }
    
    

    为图像禁用url-loader 的逻辑是,它们很少成为关键用户体验的一部分,而 HTTP2 等技术可以轻松地并行加载这些资源。

    我提出了一个问题,询问是否有更好的方法来做到这一点https://github.com/vercel/next.js/issues/17804

    【讨论】:

      猜你喜欢
      • 2020-09-28
      • 2016-10-06
      • 2021-03-04
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多