简体   繁体   English

如何从webpack生成的NPM包中正确加载资源?

[英]How to load assets correctly from webpack-generated NPM package?

I'm using webpack to generate the appropriate files for a npm package which will host a few react components. 我正在使用webpack为npm包生成适当的文件,这将包含一些反应组件。 They have some CSS attached, which references some fonts and icons. 他们附加了一些CSS,引用了一些字体和图标。

When using the file loader, these assets are mis-referenced using their absolute paths (ie fonts/my-font.woff ) in the main app which are missing. 使用file加载器时,这些资产使用主应用程序中缺少的绝对路径(即fonts/my-font.woff )进行了错误引用。

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. 我宁愿修复软件包本身而不是像有人提到的那样复制资产,因为我可能无法完全控制主应用程序。

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. 也就是说,如果字体类似于图标,您可以对它们进行base64编码并在CSS中内联。 There are several Webpack encoder plugins to do that. 有几个Webpack编码器插件可以做到这一点。

You also mentioned icons, I would try to convert these to SVG and serve them up inside the code. 你还提到了图标,我会尝试将它们转换为SVG并在代码中提供它们。 You could also base64 encode the PNGs into your CSS as a fallback. 你也可以将PNG编码为CSS作为后备。

The benefits, to this approach: 这种方法的好处:

  • Eliminating HTTP requests in the parent app 消除父应用程序中的HTTP请求
  • 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 如果您不是图标/字体的版权所有者,则可能违反TOS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM