簡體   English   中英

Webpack/React:內聯加載器執行而不被調用(來自具有動態導入的內聯加載器的意外行為)

[英]Webpack / React : Inline loader Executing Without Being Called (unexpected behaviour from inline loaders with dynamic imports)

我想做什么

我正在嘗試使用內聯加載器語法將 SVG 作為組件加載。 require(!!svg-react-loader!./path/asset.svg)並加載png, jpg圖像

我意識到使用import {Component as Asset} from "./path/to/asset.svg"加載 SVG 很容易,但是我的導入在路徑中具有動態值。

我的代碼:

const ThemedSVGWrapper = (props) => {
    const { svgName, svgProps } = props;
    const { theme } = useConfig(["theme"]);

    const SVGComponent = require(`!!svg-react-loader!./path/to/${theme}/assets/${svgName}`);

    return <SVGComponent {...svgProps}/>
}

const themedImageGetter = (theme, fileName) => {
    return require(`./themes/${theme}/assets/${fileName}`)
}
// SVGs
export const Logo = (props) => <ThemedSVGWrapper svgProps={props} svgName="logo.svg"></ThemedSVGWrapper>;
export const LoadingImage = (props) => <ThemedSVGWrapper svgProps={props} svgName="loading.svg"></ThemedSVGWrapper>;

export const getLoadingImageRef = (themeName) => themedImageRefWrap(themeName, "loading.svg");

// PNGs and JPGs
export const getLoginBackgroundImage = (themeName) => themedImageRefWrap(themeName, "Login-BG-Image.jpg");
export const getPageNotFoundImage = (themeName) => themedImageRefWrap(themeName, "page-not-found.png");

問題

使用這些導出時,我在瀏覽器中收到控制台錯誤:

./src/themes/default/assets/Login-BG-Image.jpg (./node_modules/svg-react-loader/lib/loader.js!./src/themes/default/assets/Login-BG-Image.jpg)
Error: Non-whitespace before first tag.
Line: 0
Column: 1
Char: �

在我看來,這似乎是調用svg-react-loader來加載 JPG 並拋出錯誤,因為它無法理解文件格式。

在為我的生產資產運行構建時,我得到:

...
./node_modules/svg-react-loader/lib/loader.js ^\.\/.*$ ./default/assets/Login-BG-Image.jpg
...

以及我所有其他資產的許多其他錯誤

在寫這個問題時,我意識到以下幾點:

在 ThemedSVGWrapper 中:

const SVGComponent = require(`!!svg-react-loader!./path/to/${theme}/assets/${svgName}`);

使用一個變量來確定要使用內聯加載器${svgName}加載的資產。


構建時 Webpack 會將導入中的任何變量轉換為正則表達式。

Webpack 然后使用這個正則表達式(在構建時)來確定可以加載哪些文件(在運行時)。

Webpack 然后構建一個映射到它移動到構建文件夾的資產


這意味着我使用內聯加載器通過require方法加載的資產與資產文件夾中的所有資產相匹配。

對此的簡單解決方案是將.svg添加到我的 require 函數中,以便正則表達式更加挑剔。 像這樣:

const SVGComponent = require(`!!svg-react-loader!./themes/${theme}/assets/${svgName}.svg`); 

希望這對某人有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM