Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda