无法在 React 的 require() 中使用变量

Soh*_*aib 1 html javascript node.js reactjs webpack

我通过变量数组使用图像源。我尝试了变量和反引号,但它给了我错误:错误:找不到模块'../../images/sectors/pellet-mill.png'。如果我只使用源网址,它就可以正常工作。为什么我们不能在 require() 中使用变量?

<img
     className="card-img-top"
     src={require(`${data[0].image}`)}
     alt="pellet-mill"
/>```
Run Code Online (Sandbox Code Playgroud)

jer*_*red 5

Webpack 只能捆绑它在捆绑时可以识别的资源。那么 Webpack 究竟如何知道文件require(data[0].image)代表什么?它不能,因为该文件路径仅在运行时已知,而不是捆绑/编译时。

另一种方法是提前将所有静态图像路径保存在专用 JS 文件中require()(或者更好import),然后将其用作捆绑图像的“映射”。像这样的东西:

// images.js
import image01 from './my/path/to/image01.jpg';
import image02 from './my/path/to/image02.jpg';

const images = {
  image01,
  image02
};

export default images;
Run Code Online (Sandbox Code Playgroud)
// Some component file
import images from './images.js';

function MyComponent() {
  return <img src={images.image01} />;
}
Run Code Online (Sandbox Code Playgroud)

数据的确切结构images并不重要,重要的是提前导入静态资产以便将它们捆绑起来,然后在运行时利用该结构来访问捆绑资产的概念。