Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
How to pack a JS library that contains images to be public accessible with webpack?

I have a simple library that export an <Image name="cat" /> component. The component will use the name prop to figure out the correct src value for the underlining <img /> tag.

However, I'm having trouble when bundling it with webpack (or maybe the problem itself is that I am trying to bundle it before publishing to npm). Here's some code to better paint a picture:

import cat from "../images/cat.png"
import dog from "../images/dog.png"

const images = { cat, dog }

const Image = ({ name }) => (
  <img src={images[name]} />
)
    {
      test: /\.(png|jpg|gif|svg)$/,
      use: [{
        loader: 'file-loader',
        options: {
          name: '[path][name].[ext]'
        }
      }]
    },

After I have run webpack on my library, the dist/ directory will contain a directory with both dog.png and cat.png. The transpiled minified code will have string references to them. So I publish it to npm.

Now, here's the part that gets me. When I install the published package on my project and run it, and I consume the <Image name="dog" /> component, the rendered img will still have the correct path (/images/dog.png), but webpack-dev-server hasn't realised it needs to process said file into the public directory. So in the browser, the URL resolves not on the image, but on the index.html.

Now, if instead I import the image directly to my project like import dog from "my-library/images/dog.png, then webpack correctly processes it.

I can think of a few things I'm doing wrong, but ultimately need some guidance:

  1. I shouldn't be transpiling my library through webpack before publishing it in the first place, if I'm going to consume it through npm and webpack on the consumer project.
  2. The right way of bundling assets on a library is such that the consumer project must import the asset (png) so that it webpack process it. Trying to abstract the image assets the way I'm attempting to with the Image component would never work.
  3. My webpack configuration is fundamentally flawed and I am missing information on how to do asset loading.

How should I proceed?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!