Search code examples
reactjselectronbabeljs

how to load image react babel


I'm loading icons into my app.js

import bg from './icons/bg.png';
import br from './icons/br.png';
import rg from './icons/rg.png';
import ig from './icons/invert.png';
import bw from './icons/bw.png';
import by from './icons/by.png';
import gm from './icons/gm.png';
import rs from './icons/rs.png';

They work fine when I run the default react start script, but when I try to compile using this webpack config:

const path = require('path');

module.exports = {
  mode: 'development',
  entry: './src/js/index.js',
  devtool: 'inline-source-map',
  target: 'electron-renderer',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [[
              '@babel/preset-env', {
                targets: {
                  esmodules: true
                }
              }],
              '@babel/preset-react']
          }
        }
      },
      {
        test: [/\.s[ac]ss$/i, /\.css$/i],
        use: [
          // Creates `style` nodes from JS strings
          'style-loader',
          // Translates CSS into CommonJS
          'css-loader',
          // Compiles Sass to CSS
          'sass-loader',
        ],
      }
    ]
  },
  resolve: {
    extensions: ['.js'],
  },
  output: {
    filename: 'app.js',
    path: path.resolve(__dirname, 'build', 'js'),
  },
};

I get this error for each image:

ERROR in ./src/js/icons/bg.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)
 @ ./src/js/App.js 2:0-32 230:9-11
 @ ./src/js/index.js 4:0-24 5:107-110

Which probably means that babel is trying to load the image as a javascript file. Is there a way to load an image into a Node module when compiling it with Babel and Webpack?


Solution

  • As mentioned in webpack docs

    Out of the box, webpack only understands JavaScript and JSON files.

    So you need to use loader for png file as webpack don't know what to do with that file.

    file-loader

    More on Loaders