Emma O.
Emma O.

Reputation: 25

Images not loading in React app with Webpack despite having file loaders (url-loader)

I have a React app that uses Webpack and Babel. I am trying to load an image anyway possible (svg, png...) but I keep getting the error "Unexpected character '�' (1:0) > 1 | �PNG". I installed url-loader (npm install url-loader --save-dev) which is supposed to help load images when using Webpack. Nothing has changed.

This is my webpack.config.js:

const {NODE_ENV} = process.env;

module.exports = {
  mode: NODE_ENV === 'production' ? NODE_ENV : 'development',
  entry: ['./client/index.js'],
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader'],
      },
      {
        test: /\.(png|jpg|gif)$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 25000
            }
          }
        ]
      },
    ],
  },
  resolve: {
    extensions: ['*', '.js', '.jsx'],
  },

  output: {
    path: __dirname + '/dist',
    publicPath: '/',
    filename: 'bundle.js',
  },

};

This is how I was trying to load my image:

import hiker from './hiker.png';
<img src={hiker} />

Any help would be greatly appreciated, thank you.

Upvotes: 0

Views: 1162

Answers (1)

Matt Carlotta
Matt Carlotta

Reputation: 19762

Several issues here. First, you're using babel-node that's pointing to the index.js. If you want it to point to your webpack config, then you'll need to remove index.js from the package.json's dev scripts:

"dev": "nodemon --exec babel-node",

And rename webpack.config.js to babel.config.js.

Unfortunately, there's also quite a bit more work required to get your project up-and-running. It appears that this setup uses some server-side-rendering configuration. Admittedly, I've never used koa, so I can't be of much help here.

It also appears to be a bit outdated, and someone updated it and included a walkthrough.

That said, I'd recommend steering toward a new-developer friendly boilerplate if you're just learning.

I'd suggest starting with create-react-app, which obscures a lot of this webpack configuration.

Or, you can download my react-starter-kit, which has an exposed webpack configuration that you can play around with (if desired) and utilizes webpack-dev-server for development and webpack with a very simple express configuration for production.

Up to you.

Good luck!

Upvotes: 1

Related Questions