My Vue-cli 3 project with Webpack has the following folder structure:
/public
/src
/assets
p1.jpg
p2.jpg
App.vue
main.js
I have read that in order for Webpack to recognize the /assets directory, require() should be used in JavaScript files.
This code snippet works as expected:
<template>
<div>
<ul>
<li v-for="photo in photos" :key="photo.id">
<img :src="photo.imageUrls.default" />
</li>
</ul>
</div>
</template>
<script>
/* Using require() is necessary for webpack to resolve URLs in javascript */
export default {
data() {
return {
photos: [
{
id: 1,
caption: 'P1',
series: '',
notes: '',
imageUrls: {
default: require('./assets/p1.jpg')
}
},
{
id: 2,
caption: 'P2',
series: '',
notes: '',
imageUrls: {
default: require('./assets/p2.jpg')
}
}
]
}
}
}
</script>
However, this alternative approach does not work and results in an error message in the console: "Error: Cannot find module './assets/p1.jpg'"
<template>
<div>
<ul>
<li v-for="photo in photos" :key="photo.id">
<img :src="imagePath(photo)" />
</li>
</ul>
</div>
</template>
<script>
/* To resolve URLs in javascript using webpack, require() function is needed */
export default {
data() {
return {
photos: [
{
id: 1,
caption: 'P1',
series: '',
notes: '',
imageUrls: {
default: './assets/p1.jpg'
}
},
{
id: 2,
caption: 'P2',
series: '',
notes: '',
imageUrls: {
default: './assets/p2.jpg'
}
}
]
}
},
methods: {
imagePath(photo) {
return require(photo.imageUrls.default);
}
}
}
</script>
Can someone help me understand what is incorrect in the second example? I am reluctant to use require() inside the data, as it may come from a server, which feels strange. Thank you.
EDIT: Following Edgar's recommendation, I have placed my images in a folder within the /public directory since they belong to the server and not the app. This way, I no longer need to bother with require().