フロントエンド開発といえば。
react アプリの初期化( npm init vite@latest <アプリ名> )

react で svg を import して扱う

● vite + react の場合

import された .svg は string として扱われます。

import temperatureLogo from '/temperature.svg';

console.log('● temperatureLogo');
console.log(temperatureLogo);

temperatureLogo の中身

/temperature.svg

● next.js の場合

import された .svg は オブジェクト(any型) として扱われます。

import temperatureLogo from '/temperature.svg';

console.log('● temperatureLogo');
console.log(temperatureLogo);

temperatureLogo の中身

{
  src: '/_next/static/media/temperature.2bfd6197.svg',
  height: 800,
  width: 800,
  blurWidth: 0,
  blurHeight: 0
}

ただしこのオブジェクトany型です
回避する場合は svg.d.ts を作成して tsconfig.json で読み込ませます

./src/types/svg.d.ts

interface ImportImageAttributes {
  src: string;
  height: number;
  width: number;
  placeholder?: string;
  blurWidth?: string;
  blurHeight?: string;
  blurDataURL?: string;
};

declare module '*.svg' {
  const content: ImportImageAttributes;
  export default content;
}
  "include": ["./src/types/svg.d.ts", "next-env.d.ts"],

● next.js で import した svg を Reactコンポーネントとして扱う

https://medium.com/@selmankoral/how-to-fill-your-sgv-on-react-8d67b3517c14

● SVGをコンポーネントとして使う

背景色(塗りの色)などを変更したい場合以下のようにしておくと、スタイルで背景を変えることができます:

import type { SVGProps } from "react";

export function TrashIcon({ style, ...props }: SVGProps<SVGSVGElement>) {
  return (
    <svg
      viewBox="0 0 16 16"
      fill="currentColor"
      focusable="false"
      style={style}
      {...props}
    >
      <title>Trash</title>
      <path d="M11 1.75V3h2.25a.75.75 0 0 1 0 1.5H2.75a.75.75 0 0 1 0-1.5H5V1.75C5 .784 5.784 0 6.75 0h2.5C10.216 0 11 .784 11 1.75M4.496 6.675l.66 6.6a.25.25 0 0 0 .249.225h5.19a.25.25 0 0 0 .249-.225l.66-6.6a.75.75 0 0 1 1.492.149l-.66 6.6A1.75 1.75 0 0 1 10.595 15h-5.19a1.75 1.75 0 0 1-1.741-1.575l-.66-6.6a.75.75 0 1 1 1.492-.15M6.5 1.75V3h3V1.75a.25.25 0 0 0-.25-.25h-2.5a.25.25 0 0 0-.25.25" />
    </svg>
  );
}

No.2512
02/25 06:33

edit