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)} />
说明: 您不能将变量名作为参数传递给 require,因为 webpack 不会进行程序流分析来了解变量值。
Webpack 无法知道它应该加载哪个module,因为它无法提取(猜测)有关您在变量中提供的module的任何信息(路径)。因此,当参数是变量时它无法加载。
但是,webpack 可以使用表达式,因为如果您正确提供,它可以提取有关路径的一些信息。
例如,假设这是目录结构:
example_directory
│
└───template
│ │ table.ejs
│ │ table-row.ejs
│ │
│ └───directory
│ │ another.ejs
方法 1:使用变量(不起作用):
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
方法二:使用表达式(可行;涉及一些 webpack 可以理解的模式):
var myPath = 'table'
require("./template/" + name + ".ejs")
Webpack 可以根据方法 2 中的表达式解析并生成以下上下文:
Directory: ./template // webpack understand that there is this directory
Regular expression: /^.*\.ejs$/ // and this regex about the modules
因此,它将加载所有匹配的module:
./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
。它加载所有匹配的module并生成一个“上下文module”,作为上述表达式的结果,它包含所有此类加载module的信息。
因此,您需要提供一个 webpack 可以理解的表达式,并通过加载所有匹配项来制作上下文module。
这意味着支持动态需求,但会导致所有匹配的module都包含在包中。(并且可能会增加包的大小,因此在使用 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"
您也可以使用反引号,即模板文字:
`../images/${src}.png`