If you want to leverage the power of a composable, consider the following approach:
composables/useAssets.js
import fs from 'fs';
import path from 'path';
const folderPath = './public';
const relativeFolderPath = path.relative(process.cwd(), folderPath);
export default function () {
const files = fs
.readdirSync(folderPath)
.filter((file) => file.match(/.*\.(jpg|png?)/gi));
const filesPaths = files.map(
(fileName) => `/_nuxt/${relativeFolderPath}/${fileName}`
);
return filesPaths;
}
YourComponent.vue
<script setup>
const assets = useAssets();
</script>
<template>
<div>
<img :src="item" v-for="item in assets" :key="item" />
</div>
</template>
The code above helps you extract all files within a specified folder by configuring folderPath
. It then determines the relative path of this folder from the project root for later concatenation with file paths (process.cwd()
retrieves the project's root path).
Once the assets matching the criteria are identified and stored in the array files
, the map
function is used to generate a new array containing correctly formatted relative paths to ensure correct interpretation by nuxt.