[英]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 以在将模块作为依赖项的应用程序中包含模块资产。
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:但是,当我运行它时,我遇到了两个问题:
image.png
is sought at the root directory image.png
在根目录下查找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 以上的图像。
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 进程捆绑
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.
观点是这些将被推送到构建目录。
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.