1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

create-react-app(typescript)で作成したプロジェクトにて、画像を読み込めるように

Posted at

解決に結構時間がかかったためメモ!

起こったこと

フォルダ構成(一部省略)
project/
 └ src/
   ├ Hoge.tsx
   └ fuga.png

create-react-app [project名] --template typescriptで作成したプロジェクト(フォルダ構成は上記)にて、画像が表示されない...
(コードは以下です。)

Hoge.tsx
const Hoge = () => {
    return <div>
        <img src="./fuga.png" alt="" />{/* ← 表示されない... */}
    <div>
};

解決法

下記の手順で解決可能です!

  1. 画像はimportで読み込むようにする
  2. 画像用の型定義ファイルを作成する。

1. 画像はimportで読み込むようにする

読み込む画像ファイルをwebpackにバンドル対象として伝えるために本手順を踏む必要があるみたいです!

詳細(公式サイト)→https://create-react-app.dev/docs/adding-images-fonts-and-files/

Hoge.tsx
// ↓ 画像をimportで読み込む
import fugaImage from './fuga.png';

const Hoge = () => {
    return <div>
        <img src={fugaImage} alt="" />{/*  */}
    <div>
};

ですが、これだけだとまだ下記のエラー(読み込んだモジュールの型定義が見つからないよ)が出てしまいます。
TS2307: Cannot find module './fuga.png' or its corresponding type declarations.
上記エラーを手順2で解決します!

2. 画像用の型定義ファイルを作成する。

srcと同じ階層にtypesのフォルダ(型定義用)を作成し、
そこに下記の型定義ファイルを設置します。

types/index.d.ts
declear module '*.png' { // pngファイルが対象
    const url: string;
    export default url; // importしたときにstringで読み込まれるよ
}

※フォルダ構成は下記のようになります。

フォルダ構成(一部省略)
project/
 ├ src/
 │ ├ Hoge.tsx
 │ └ fuga.png
 └ types/
   └ index.d.ts

するとHoge.tsxが画像(fugaImage)をエラーなしで読み込めるようになります!

※間違いなどございましたら気兼ねなくおっしゃっていただければ幸いです!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?