LoginSignup
8
9

More than 3 years have passed since last update.

React + Next.jsで画像をimportする

Last updated at Posted at 2019-10-20

困ったこと

Reactで画像のパスが読み込めない

logo.tsx
const logo = require('../../assets/images/logo.png')
// =>
// [ error ] ./src/assets/images/logo.png 1:0
// Module parse failed: Unexpected character '�' (1:0)
// You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See 
// https://webpack.js.org/concepts#loaders
// (Source code omitted for this binary file)

原因

画像ファイルのパスをパースできない

解決

  1. url-loaderを追加する
  2. next.config.js にその設定を追加する
yarn add url-loader
next.config.json
module.exports = withSass(withTypescript({
    [...]
    // ここから
    config.module.rules.push({
      test: /\.(png|jpg|gif|svg)$/,
      use: {
        loader: 'url-loader',
        options: {
          limit: 100000
        }
      }
    })
    // ここまで

    return config;
  }
}));

画像の読み込み方について

importよりrequire使った方がよさそう。

logo.tsx
const logo = require('../../assets/images/logo.png')

参考ページ

8
9
1

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
8
9