網站搜尋

reactjs - 使用 Rollup 導入圖片僅複製檔案並保留導入


我花了很多時間,並嘗試了一些與 Rollup 搭配的插件來保留正常的圖片導入。

當我使用 tsc 編譯時,我在編譯上沒有問題,因為我的圖片導入是從以下位置編譯的:

import myImage from '../../images/my-image.jpg'

到

const myImage = tslib_1.__importDefault(require( '../../images/my-image.jpg'));

但現在使用 rollup 時,我唯一找到的導入圖片的正確方式是使用 @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,但也遇到了路徑問題。

我最後想到的解決方案是,在 rollup 中忽略影像解析,只使用 copy 插件複製 images 資料夾。但我不知道如何在 rollup 中忽略那些檔案的解析。

謝謝,如果不清楚或需要更詳細的說明,請隨時向我提問。

答案#1

我遇到了同樣的問題,並且找不到一個能完全符合我需求的現有插件。

我最後寫了這個小插件,讓我可以通過在 resolveId 鉤子中將它們標記為 external 來忽略圖片匯入。這樣它們在庫中就會保留為例如 import whatever from "assets/whatever.png",所以使用該庫的應用程式的打包工具可以按照它想要的方式處理這個圖片。

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 };
    },
  };
}

然後我在我的情況下從 rollup 插件配置中這樣使用它,專門針對 .png 圖像文件的導入:

import copy from "rollup-plugin-copy";

const copyTargets = [];

...

plugins: [
    externalAsset({
        include: [".png$"],
        copyTargets: copyTargets,
        assetTargetDir: "dist/assets",
    }),
    copy({ targets: copyTargets, verbose: true }),
]

然後我將那些圖像路徑提供給 rollup-plugin-copy 插件,該插件會將被忽略的圖像文件複製到發佈目錄中。