Webpack 5 Asset Modules not bundling images in

Viewed 1069

I'm trying to use the new webpack 5 feature Asset Modules to include a static png image in my react library. This should be a basic task but I'm pulling my hair out trying to figure out why the image is not being included. I've done the following things.

  1. Included the rule as part of webpack.config.js
module.exports = {
    entry: './index.ts',
    output: {
        filename: 'index.js',
        path: __dirname,
        assetModuleFilename: 'assets/[hash][ext][query]'
    },
    module: {
        rules: [
          {
            test: /\.png/,
            type: 'asset/resource'
          }
        ]
    },
};
  1. Imported and used the image in a component
import React from 'react';
import image from '../src/assets/transport-belt-down.png'

function RenderedSquare(props: RenderedSquareProps){
    return <img src={image}>image</img>
}

export { RenderedSquare };

This component is the only thing rendered in index.ts, so the image is definitely being used.

However the image does not get included in the dist folder when I run tsc. This means on consuming the library you get the following error .

../factorio-blueprint-renderer/src/assets/transport-belt-down.png
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

Things I have tried

  • Use a jpg instead of a png
  • Regress to file-loader and url-loader instead
  • Manually include the assets folder in webpack.config.js
  • Move the image to src
  • Use require() instead of import
  • Use relative / direct import
  • Prayed to my various gods
1 Answers

Can you change the value of 'assetModuleFilename' in output and 'rules' in module. It worked for me.

output: {
    filename: 'index.js',
    path: __dirname,
    assetModuleFilename: 'assets/[name][ext]'
},
  module: {
    rules: [
        {
            test: /\.(png|svg|jpg|jpeg|gif)$/i,
            type: 'asset/resource',
        },
    ]
}
Related