I use the webpack plugin with the default settings. The following code throws an unexpected error:
<test-component src="@/assets/img/test.jpg"></test-component>
<template>
<img :src="requireImage" />
</template>
<script>
export default {
name: 'test-component',
props: {
image: {type: String, required: true},
},
computed: {
// Via: http://vuejs-templates.github.io/webpack/static.html
requireImage() {
return require(this.image); // This throws the error
// return require('@/assets/img/test.jpg'); // This is the exact string gotten from the prop, this does not throw an error?
}
}
}
</script>
The errors:
[HMR] bundle has 1 warnings
client.js?7955:161 ./~/vue-loader/lib/template-compiler.js?{"id":"data-v-f38160c0"}!./~/vue-loader/lib/selector.js?type=template&index=0!./test-component.vue
10:13-31 Critical dependency: the request of a dependency is an expression
vue.esm.js?65d7:564
[Vue warn]: Error in render function:
(found in <testcomponent> at test-component.vue)
warn @ vue.esm.js?65d7:564
handleError @ vue.esm.js?65d7:1445
Vue._render @ vue.esm.js?65d7:3520
updateComponent @ vue.esm.js?65d7:2095
get @ vue.esm.js?65d7:2414
Watcher @ vue.esm.js?65d7:2397
mountComponent @ vue.esm.js?65d7:2109
Vue$3.$mount @ vue.esm.js?65d7:7156
Vue$3.$mount @ vue.esm.js?65d7:9157
init @ vue.esm.js?65d7:3005
createComponent @ vue.esm.js?65d7:4526
createElm @ vue.esm.js?65d7:4469
updateChildren @ vue.esm.js?65d7:4744
patchVnode @ vue.esm.js?65d7:4807
patch @ vue.esm.js?65d7:4931
Vue._update @ vue.esm.js?65d7:1996
updateComponent @ vue.esm.js?65d7:2099
get @ vue.esm.js?65d7:2414
run @ vue.esm.js?65d7:2484
flushSchedulerQueue @ vue.esm.js?65d7:2278
(anonymous) @ vue.esm.js?65d7:459
nextTickHandler @ vue.esm.js?65d7:408
vue.esm.js?65d7:1449 Error: Cannot find module "."
So basically, requiring the variable throws an error, but requiring the output of the variable works perfectly. Am I missing something here or is this somehow a bug?
You can't make webpack require a resource that is only an expression (which is only evaluated at runtime) - which makes sense, because the require could end up being anything, includeing a node_modules package, and webpack shouldn't pre-load all of those possibly hundreds of megabytes of files, right?
You can however use a partly dynmaic require string:
https://webpack.js.org/guides/dependency-management/#require-with-expression
You can try concatenating the string in Computed. Something like this
computed: {
image() {
return require("@/assets/images/modals/aiesec/" + this.ima);
}
}
Most helpful comment
You can't make webpack require a resource that is only an expression (which is only evaluated at runtime) - which makes sense, because the require could end up being anything, includeing a node_modules package, and webpack shouldn't pre-load all of those possibly hundreds of megabytes of files, right?
You can however use a partly dynmaic require string:
https://webpack.js.org/guides/dependency-management/#require-with-expression