reactjs - 仅文件复制和保留导入的汇总图像导入
问题描述
我花了很多时间尝试一些带有汇总的插件来保留正常的图像导入。
当我使用 tsc 进行编译时,我的编译没有问题,因为我的图像导入是从以下位置编译的:
import myImage from '../../images/my-image.jpg'
至
const myImage = tslib_1.__importDefault(require( '../../images/my-image.jpg'));
但是现在有了汇总,我发现导入图像的唯一正确方法是使用,@rollup/plugin-image
但由于 base64 转换,它增加了 30% 的包大小。
我试过@rollup/plugin-url
了,但是这个插件创建了一个my-image.js
导出我的图像路径的文件。当从其他应用程序导入组件时,这不起作用,因为 webpack(例如)不理解必须导入此路径。
我也试过rollup-plugin-rebase
了,这确实是我要找的,但是 preserveModule 有问题,所以导入是这样捆绑的
import myImage from '../Title/my-image.jpg' (Title is the last folder on the same subfolder)
我也尝试过rollup-plugin-smart-assets
,但也遇到了路径问题。
我想的最后一个解决方案是忽略汇总中的图像解析,只使用复制插件复制图像文件夹。但我不知道如何忽略汇总中的那些文件解析。
谢谢,如果不清楚还是需要更精确,请随时问我。
解决方案
I had the same problem and couldn't find an existing plugin that did exactly what I wanted.
I ended up writing this small plugin to let me ignore image imports by marking them as external
in the resolveId
hook. That leaves them as for example import whatever from "assets/whatever.png"
in the library, so the consuming application's bundler can handle this image how it wants to.
function externalAsset({ include, copyTargets, assetTargetDir }) {
const isMatchSingle = function (include, module) {
return new RegExp(include, "g").test(module);
};
const isMatch = function (include, module) {
if (include === undefined) return true;
return Array.isArray(include) ? include.some((i) => isMatchSingle(i, module)) : isMatchSingle(include, module);
};
return {
name: "rollup-plugin-external-asset",
resolveId(source) {
if (!isMatch(include, source)) return null;
copyTargets && copyTargets.push({ src: source, dest: assetTargetDir });
return { id: source, external: true };
},
};
}
Which I then use from the rollup plugins config like this in my case to target imports of .png image files specifically:
import copy from "rollup-plugin-copy";
const copyTargets = [];
...
plugins: [
externalAsset({
include: [".png$"],
copyTargets: copyTargets,
assetTargetDir: "dist/assets",
}),
copy({ targets: copyTargets, verbose: true }),
]
I then feed those image paths to the rollup-plugin-copy plugin which copies the ignored image files into the distribution.
推荐阅读
- google-search - Google Custom Search Site Restricted JSON API 超过 10 个站点
- java - 如何将 ApiParam 传递给另一个变量的验证器?
- sql-server - 如何在 SQL Server 2008 中将 dbo 所有权更改为另一个用户登录?
- java - 使用for循环解除阻塞“保持”的方法?
- curl - 我们如何使用 curl 搜索 nexus repo 标签?
- java - 使用 gradle 在 Jar 中包含 pom.xml
- keras - LSTM 网格搜索
- r - 分割不同长度的字符串
- python - 解决python中列表的问题
- c# - C# ASP.NET MVC 脚本被加载两次