批量反应导入图标/图像

Dee*_*ndi 5 javascript import reactjs webpack

我有 100 个要导入的图标和图像。有什么办法可以消除在页面顶部写这么多导入语句?我想在一个单独的文件中编写一个导入语句并将其嵌入到顶部。

import basicAmenitiesIcon from '../../../../images/icons/wifi-sign.png';
import parkingIcon from '../../../../images/icons/parking.png';
...
Run Code Online (Sandbox Code Playgroud)

有没有其他办法解决?我正在使用 webpack,这是配置:

{
    test: /\.(jpe?g|png|gif|svg)$/i,
    loaders: [
        'file?hash=sha512&digest=hex&name=[hash].[ext]',
        'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
    ]
}
Run Code Online (Sandbox Code Playgroud)

Tud*_*soi 5

是的,这是可能的,请在此处查看我的答案:https : //stackoverflow.com/a/41410938/646156

var context = require.context('../../../../images/icons', true, /\.(png)$/);
var files={};

context.keys().forEach((filename)=>{
  files[filename] = context(filename);
});
console.log(files); //you have file contents in the 'files' object, with filenames as keys
Run Code Online (Sandbox Code Playgroud)