soc*_*var 13 javascript webpack vue.js
我正在尝试将图像 src 动态绑定到表单的 URL ../assets/project_screens/image_name.jpg。
我的目录结构如下:
- src
-- assets
---- project_screens
-- profile
---- ProjectList.vue
-- store
---- profile.js
Run Code Online (Sandbox Code Playgroud)
我知道我需要使用 webpackrequire("path/to/image")来帮助 webpack 构建这些图像,但是路径没有解析。
- src
-- assets
---- project_screens
-- profile
---- ProjectList.vue
-- store
---- profile.js
Run Code Online (Sandbox Code Playgroud)
// store/profile.js
projects = [
{
....
},
{
....
img_url: "../assets/project_screens/im1.jpg"
....
}
....
]
Run Code Online (Sandbox Code Playgroud)
如果我使用 URL 字符串而不是动态传递 URL 字符串,它会起作用。环顾堆栈溢出,没有任何解决方案有帮助。我还缺少其他东西吗?
soc*_*var 20
我终于想通了!!如果文件名称完全以变量形式给出,则 Webpack 无法导入文件,例如:
require(imageUrl) // doesn't work
Run Code Online (Sandbox Code Playgroud)
这是因为如果路径存储在变量中,它在编译时不知道路径。
但是 Webpack 可以在 require() 中给定字符串插值时检测要捆绑的文件,例如:
require(`../assets/profile_screens/${filename}`) // Works
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为 Webpack 在编译时知道路径“../assets/profile_screens”,因此它可以包含文件夹中的所有文件。