Nuxt 动态资产未加载 [英] Nuxt dynamic asset not loading
问题描述
我正在尝试在 nuxt
中加载动态资产.我遵循了所有建议,说应该使用 require
但我无法让它工作.
I'm trying to load dynamic assets in nuxt
. I followed all the advice saying one should use require
but I can't get it to work.
在我的模板中,
<v-img :src="mimeTypeUrl()"></v-img>
以下导致错误:找不到模块'~/assets/media/application-vnd-google-earth-kmz.png'"
methods: {
mimeTypeUrl() {
const f = '~/assets/media/application-vnd-google-earth-kmz.png';
return require(f);
}
}
但这工作正常:
methods: {
mimeTypeUrl() {
return require('~/assets/media/application-vnd-google-earth-kmz.png');
}
}
这里有什么问题,我该如何解决?
What's the problem here and how can I solve this?
@nuxt/核心版本:2.11.0
webpack 版本:4.41.6
推荐答案
这总是一个棘手的情况.在您的情况下,您可以通过将 f
别名为图标名称来解决此问题,并在路径内将其串联使用:
This is always a tricky situation. In your case, you can solve this by aliasing the f
to the icon name, and using it in place, concatenated, within the path:
mimeTypeUrl(icon) {
return require(`~/assets/media/${icon}`);
}
然后使用图标作为参数调用它:
And then calling it with the icon as an argument:
:src="mimeTypeUrl('application-vnd-google-earth-kmz.png')"
这是可行的,因为 webpack 将为您的 /assets/media
目录创建一个完整的上下文,其中将包含您的图像文件.
This works because webpack will create an entire context for your /assets/media
directory, which will contain your image file.
不推荐
你可以通过在你的路径前面加上一个空字符串来为你的整个项目创建一个上下文来欺骗 webpack
You may be able to actually trick webpack by creating a context for your entire project by prepending your path with an empty string
mimeTypeUrl(icon) {
return require('' + '~/assets/media/application-vnd-google-earth-kmz.png');
}
这不是我们想要的,因为它会为您的整个应用程序结构创建上下文,从而将包的大小增加可测量的数量.如果文件和/或类的命名发生冲突,它也可能通过污染全局上下文并使其别名解析不正确而产生意想不到的后果.
This is not desired because it will create context for your entire application structure which will increase the bundle size by a measurable amount. It may also have unintended consequences by polluting the global context and making it so aliases resolve incorrectly if there is a collision in the naming of files and or classes.
这篇关于Nuxt 动态资产未加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!