TLDR;
// All of these works
const fileNameExt = 'foo.jpg'
<img src={require('../images/' + fileNameExt)} />
<img src={require(`../images/${fileNameExt}`)} />
const fileName = 'foo'
<img src={require('../images/' + fileName + '.jpg')} />
<img src={require(`../images/${fileName}.jpg`)} />
// These does not work:
const myPathVariable1 = '../images/' + 'foo' + '.jpg'
<img src={require(myPathVariable1)} />
const myPathVariable2 = '../images/' + 'foo.jpg'
<img src={require(myPathVariable2)} />
解释: You can not pass a variable name as argument to require 因为 webpack 不做程序流分析来知道变量值。
Webpack 无法知道它应该加载哪个模块,因为它无法提取(猜测)关于您在变量中提供的模块的任何信息(路径)。因此,当参数是变量时加载失败。
但是,webpack 可以require with expression 因为它可以提取一些关于路径的信息如果你提供正确。
例如,假设这是目录结构:
example_directory
│
└───template
│ │ table.ejs
│ │ table-row.ejs
│ │
│ └───directory
│ │ another.ejs
方法一:使用变量(不起作用):
var myPath = './template/table-row.ejs'
require(myPath)
// will not work as webpack can't extract anything path or file as myPath is just a variable
方法2:使用表达式(可行;涉及一些webpack可以理解的模式):
var myPath = 'table'
require("./template/" + name + ".ejs")
Webpack可以从方法2中的表达式解析生成context以下:
Directory: ./template // webpack understand that there is this directory
Regular expression: /^.*\.ejs$/ // and this regex about the modules
所以,它会加载所有匹配的模块:
./template/table.ejs
./template/table-row.ejs
./template/directory/another.ejs
// Note that it will load all matching even if we provide --> var myPath = 'table' shown above
所以,每当 webpack 在 require 中看到“表达式”(不是变量)时。它加载所有匹配的模块并生成一个“Context Module”,其中包含所有此类加载模块的信息作为上述表达式的结果。
因此,您需要提供一个 webpack 可以理解的表达式,并通过加载所有匹配项来制作上下文模块。
这意味着支持动态需求,但会导致捆绑包中包含所有匹配的模块。 (并且可能会增加你的包大小,所以在使用 require 中的表达式时需要小心)
回答你的问题:
要完成这项工作:
<img className='personal' alt='robots' src={require(`${src}`)}/>
你需要做的:
<img className='personal' alt='robots' src={require("../images/" + src)}/>
// loads everyting inside "../images/"
或者,更好:
<img className='personal' alt='robots' src={require("../images/" + src + ".png")}/>
// loads everything inside "../images/" ending with ".png"
您也可以使用反引号,即template literals:
`../images/${src}.png`