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

如何在Turborepo的tsup包中配置SVGR

在Turborepo的tsup UI包中配置SVGR

1. 安装依赖

在项目根目录执行以下命令,给ui包安装SVGR所需的Rollup插件:

pnpm add -D @svgr/rollup --filter ui

2. 修改tsup配置文件

更新packages/ui/tsup.config.ts,引入SVGR插件并调整配置,让tsup能处理SVG文件:

import type { Options } from "tsup";
import { defineConfig } from "tsup";
import svgr from "@svgr/rollup";

export default defineConfig((options: Options) => ({
  plugins: [svgr()],
  treeshake: true,
  splitting: true,
  entryPoints: ["./**/*.tsx", "./**/*.svg"],
  dts: true,
  minify: true,
  clean: true,
  externals: ["react"],
  ...options,
}));

如果需要自定义SVG转换规则(比如启用SVGO压缩、保留viewBox属性等),可以给svgr()传入配置参数:

svgr({
  svgo: true,
  svgoConfig: {
    plugins: [{ removeViewBox: false }]
  },
  titleProp: true, // 自动为SVG添加title属性
})

3. 配置TypeScript类型支持

在packages/ui目录下创建typings/svg.d.ts文件,添加SVG模块的类型声明,让TS能识别SVG导入:

declare module "*.svg" {
  import React from 'react';
  const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;
  export default ReactComponent;
}

同时确保packages/ui/tsconfig.json中包含该类型目录:

{
  "compilerOptions": {
    // 其他已有配置
    "typeRoots": ["./typings", "./node_modules/@types"]
  }
}

4. 使用SVG组件

在UI组件中直接导入SVG文件,当作React组件使用:

// packages/ui/components/Logo.tsx
import React from 'react';
import LogoIcon from './logo.svg';

export const Logo = () => {
  return <LogoIcon className="w-8 h-8 text-blue-500" />;
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 22:55:08