简体   繁体   English

Webpack 5 - 如何从 npm 模块捆绑资产

[英]Webpack 5 - how to bundle assets from an npm module

I have built an npm module.我已经构建了一个 npm 模块。 I am struggling to find a way to configure webpack 5 to include module-assets in an app that has the module as a dependency.我正在努力寻找一种方法来配置 webpack 5 以在将模块作为依赖项的应用程序中包含模块资产。

Context语境

What I have is something like:我所拥有的是这样的:

myNpmModule

dist/
    index.js
    assets/
        image.png

I use the module as follows我使用模块如下

// project/app.jsx
import Component from 'myNpmModule'
return <Component />

In this example, <Component /> renders image.png .在此示例中, <Component />呈现image.png

When I run this however I have two problems:但是,当我运行它时,我遇到了两个问题:

  1. image.png is sought at the root directory image.png在根目录下查找
  2. image.png is not in the webpack bundle image.png不在 webpack 包中

To get around this issue I have converted all images in myNpmModule to data URL's using the webpack asset module ("asset/inline").为了解决这个问题,我使用webpack 资产模块(“资产/内联”)将myNpmModule中的所有图像转换为数据 URL。 This is an approach I've copied from bootstrap and it works.这是我从 bootstrap 复制的一种方法,并且有效。 The problem is the file size of app.jsx , as it includes numerous 1MB+ images.问题是app.jsx的文件大小,因为它包含许多 1MB 以上的图像。

Similar questions and issues I've found我发现的类似问题和问题

The question is tied to scss processing, rather than the inclusion of images in .js files.这个问题与 scss 处理有关,而不是在.js文件中包含图像。 I've read the resolve modules documentation for webpack I couldn't see a way to tie it to a solution.我已经阅读了webpack 的解决模块文档,但我看不到将其与解决方案联系起来的方法。

This effectively copies the assets from node_modules/myNpmModule/dist/assets to your build directory, which is hacky.这有效地将资产从node_modules/myNpmModule/dist/assets复制到你的构建目录,这是 hacky。 From what I can tell I'd need to modify myNpmModule to only ever look for assets in that destination directory which doesn't scale.据我所知,我需要修改myNpmModule以仅在无法扩展的目标目录中查找资产。

Recommends you use new URL('./image.png', import.url.meta) to import the images.建议您使用new URL('./image.png', import.url.meta)导入图片。 That doesn't work - or at least the images aren't bundled by the webpack process for project/app.jsx这不起作用 - 或者至少图像没有被project/app.jsx的 webpack 进程捆绑

My questions我的问题

One approach I've thought of is to configure webpack to convert data URL's into files during the webpack build process.我想到的一种方法是配置 webpack 以在 webpack 构建过程中将数据 URL 转换为文件。 The view is that these would then be pushed to the build directory.观点是这些将被推送到构建目录。

  1. is there a webpack loader to convert data URL's into files?是否有 webpack 加载程序将数据 URL 转换为文件?
  2. is there a better approach?有更好的方法吗?

Unfortunately none of these give satisfactory answers for 3rd parties that will be installing my myNpmModule .不幸的是,这些都没有为将安装我的myNpmModule的第 3 方提供令人满意的答案。

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

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