动态引入svg失败,改用img实现gallery

2025年5月30日 Mr 焦 151

在nextjs项目中,有/public/images/icon目录,其中有很多svg图标。我希望做一个gallery页面,展示这些svg,但不能使用![]()元素,因为fill和stroke属性会无法生效,一些没有任何颜色的svg会显示不出来。

项目在next.config.js中配置了@svgr/webpack

{
  test: /\.svg$/i,
  issuer: /\.[jt]sx?$/,
  use: [
    {
      loader: '@svgr/webpack',
      options: {
        typescript: true,
        icon: true
      }
    }
  ]
}

服务端组件引入svg会报错

// Module parse failed: Unexpected token (1:0)
// You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
import BanIcon from 'public/images/icon/insights/ban.svg'

use client + 动态引入,不行

'use client'
import dynamic from 'next/dynamic';

export default async function ClientSvg(path) {
  // 成功加载
  const Svg = dynamic(() => import('public/images/icon/menu/icon_topview.svg'), { ssr: false }) 

  // 失败的加载,将path整个传入
  // Cannot find module 'public/images/icon/menu/icon_topview.svg'
  const Svg = dynamic(() => import(path), { ssr: false }) 

  // 失败的加载,将path部分传入
  // 虽然配置了webpack-loader,但无效
  // Module parse failed: Unexpected token (1:0)
  // You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
  const Svg = dynamic(() => import('public/images/icon/menu/${path}.svg'), { ssr: false }) 

  return <p>

  </p>
}

有没有webpack魔法注释可以解决上面的loader问题?没有

尝试另一种引入方法,无效

const svgDir = require.context("!@svgr/webpack!../../assets/svg/");
const Icon = svgDir("./Group 9.svg").default

目前仍然找不到合适的方法动态引入svg

转换思路

使用 img 标签来展示 svg 图标,对于没有颜色的 svg 无法显示的问题,只需要对 svg 设置 fill="currentColor" stroke="currentColor" 即可在 img 标签中渲染出有颜色的图案。

详细代码: https://gist.github.com/Jiny3213/8f6fbcb1f04299fee58ad1036a7247a9

分类:
标签:
版权属于Mr 焦
本文链接:https://www.mtsws.cn/post-14.html
评论
暂无评论数据