首页 > 解决方案 > 仅文件复制和保留导入的汇总图像导入

问题描述

我花了很多时间尝试一些带有汇总的插件来保留正常的图像导入。

当我使用 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,但也遇到了路径问题。

我想的最后一个解决方案是忽略汇总中的图像解析,只使用复制插件复制图像文件夹。但我不知道如何忽略汇总中的那些文件解析。

谢谢,如果不清楚还是需要更精确,请随时问我。

标签: reactjstypescriptimagerollupstatic-files

解决方案


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.


推荐阅读