0
1

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 5 years have passed since last update.

ディレクトリ下の画像ファイルを動的に読み込む

Last updated at Posted at 2020-05-24

やりたいこと

特定のディレクトリ下に画像ファイルを追加したらコード自体には一切手を加えずその画像が表示されるようにしたい。

結論

import React from 'react';

function App() {
  const importAll = (r: __WebpackModuleApi.RequireContext) => {
    return r.keys().map(v => r(v) as string);
  }

  const images = importAll(require.context('./assets/images', false, /\.(png|jpe?g|svg)$/));

  return (
    <>
      {images.map(image => <img src={image} key={image} alt={image} />)}
    </>
  );
}

require.context()で読み込むファイルを探すディレクトリと正規表現を指定して対象ファイルのパスを取得できる。

RequireContextの戻り値がanyなので、 公式ドキュメントのようにreturn r.keys().map(r) すると unknown[] となる。
今回は画像を読み込んでいるためsrcに突っ込むためにstringにキャストしている。

ドキュメント

参考記事

https://qiita.com/proudust/items/d716957e243f9e019fda
https://qiita.com/jkr_2255/items/d23e66323857d3189a00

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?