How to load assets correctly from webpack-generated NPM package?
Asked Answered
S

1

22

I'm using webpack to generate the appropriate files for a npm package which will host a few react components. They have some CSS attached, which references some fonts and icons.

When using the file loader, these assets are mis-referenced using their absolute paths (i.e. fonts/my-font.woff) in the main app which are missing.

Is there a way to fix this and make my main app look for the right files? I'd rather fix the package itself than doing things like copying the assets like someone has mentioned as I may not have full control of the main app.

Silvester answered 11/5, 2016 at 19:32 Comment(0)
C
4

Well, I'm going to preface this by saying that including fonts in a component is usually a bad idea since the main app likely has its own style/branding/etc that you'll be fighting with.

That said, if the fonts are something like icons you could base64 encode them and inline that in the CSS. There are several Webpack encoder plugins to do that.

You also mentioned icons, I would try to convert these to SVG and serve them up inside the code. You could also base64 encode the PNGs into your CSS as a fallback.

The benefits, to this approach:

  • Eliminating HTTP requests in the parent app
  • Parent app always has the latest (non-cached) icons/fonts when you update your package
  • You don't have to worry about paths, packaging external files, etc

Cons I can think of:

  • You're increasing script sizes significantly
  • You lose some caching benefits
  • If you're not the copyright owner of the icons/fonts, this may violate TOS
Cervin answered 10/2, 2019 at 18:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.