Webpack 动态导入表达式不起作用

Webpack Dynamic Import Expression Not Working

我正在使用 react with webpack。

我有一个文件夹,里面有数百个 SVG。
因此,我正在使用像 import('../images_svg/' + svgData.path + '.svg') 这样的 webpacks 动态导入语法,遗憾的是这不起作用。我也在使用 svg-inline-loader。

这就是我得到以下异常的原因:

<--- Last few GCs --->

   95733 ms: Mark-sweep 1301.0 (1434.6) -> 1303.2 (1434.6) MB, 61.8 / 0.0 ms [allocation failure] [scavenge might not succeed].
   95794 ms: Mark-sweep 1303.2 (1434.6) -> 1305.4 (1434.6) MB, 60.9 / 0.0 ms [allocation failure] [scavenge might not succeed].
   95856 ms: Mark-sweep 1305.4 (1434.6) -> 1312.2 (1418.6) MB, 62.3 / 0.0 ms [last resort gc].
   95922 ms: Mark-sweep 1312.2 (1418.6) -> 1319.1 (1418.6) MB, 65.9 / 0.0 ms [last resort gc].


<--- JS stacktrace --->

==== JS stack trace =========================================

Security context: 000001788583FA99 <JS Object>
    1: stringify [native json.js:178] [pc=000002CFEA0A3CF7] (this=0000017885846091 <a JSON with map 0000010551613B91>,E=0000023A39E19981 <Very long string[11977826]>,F=0000017885804241 <undefined>,S=0000017885804241 <undefined>)
    2: arguments adaptor frame: 1->3
    3: /* anonymous */ [C:\Users\phili\Documents\Kunden\step1\app\node_modules\webpack\lib\EvalDevToolModuleTemplatePlugin.js:~17...

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory 

如何使用 webpack 动态导入所有 SVG,而不会出现堆内存不足错误?

更新解决方案

非常感谢 Dan Abramov(Redux 的创建者)。他建议我使用 create-react-app 自述文件中描述的 public 文件夹,并且不要通过 webpack 导入 SVG:
Adding asssets outside of the module system

create-react-app 自述文件指出:

Normally we recommend importing stylesheets, images, and fonts from JavaScript. The public folder is useful as a workaround for a number of less common cases:

其中一个案例是:

You have thousands of images and need to dynamically reference their paths.

所以现在我正在使用这个 fetch 库,它已经包含在配置中(由 create-react-app 弹出后生成)

使用 fetch,我可以从 public 文件夹动态加载图像并启动 webpack,而不会再出现内存问题。


旧解

一个解决方案是使用

node --max_old_space_size=8000 scripts/start.js

让它工作。但是加载大约需要 10 分钟。为了让它启动得更快,我们可以使用 webpack 的 cache-loader。 因此我将加载时间减少到一分钟。

看到这个问题的线程https://github.com/webpack/webpack/issues/5747