You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS 13新目录结构(src/app)下SVG导入问题求助

Next 13 /app目录下实现SVG导入的可行方案

在Next 13的/app目录结构下,需要调整webpack配置来适配@svgr/webpack,以下是经过验证的实现步骤:

  • 安装依赖
    确保已安装@svgr/webpack:

    npm install @svgr/webpack --save-dev
    # 或使用yarn/pnpm
    yarn add @svgr/webpack -D
    pnpm add @svgr/webpack -D
    
  • 修改next.config.js配置
    Next 13对SVG有默认的资源处理规则,需先排除该规则,再添加SVGR的处理逻辑:

    /** @type {import('next').NextConfig} */
    const nextConfig = {
      webpack(config) {
        // 移除Next.js默认的SVG处理规则
        config.module.rules = config.module.rules.map(rule => {
          if (rule.test?.test?.('.svg')) {
            return { ...rule, exclude: /\.svg$/i };
          }
          return rule;
        });
    
        // 添加SVGR的SVG组件化处理规则
        config.module.rules.push({
          test: /\.svg$/i,
          issuer: /\.[jt]sx?$/, // 仅处理JSX/TSX文件中导入的SVG
          use: ['@svgr/webpack'],
        });
    
        return config;
      },
    };
    
    module.exports = nextConfig;
    
  • 添加TypeScript类型声明(可选但推荐)
    如果使用TypeScript,在项目根目录或src/types下创建svg.d.ts文件,避免类型报错:

    declare module '*.svg' {
      import type React from 'react';
      const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;
      export default ReactComponent;
    }
    
  • 在/app目录中使用SVG组件
    导入后直接以React组件方式使用:

    import Logo from '@/assets/logo.svg';
    
    export default function Home() {
      return (
        <main>
          <Logo width={120} height={120} fill="#000" />
        </main>
      );
    }
    
  • 同时支持SVG组件和资源URL(可选)
    若需同时将SVG作为组件和静态资源使用,调整webpack配置中的SVGR选项:

    // 在next.config.js的webpack规则中修改use部分
    use: [
      {
        loader: '@svgr/webpack',
        options: { exportType: 'named' },
      },
    ],
    

    使用时分别导入:

    import { ReactComponent as Logo } from '@/assets/logo.svg';
    import logoUrl from '@/assets/logo.svg';
    
    // 作为React组件使用
    <Logo />
    // 作为图片资源使用
    <img src={logoUrl} alt="Site Logo" />
    

内容的提问来源于stack exchange,提问作者AbrahamDN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 12:55:37