I'm encountering a problem with structuring assets in the output directory while utilizing Vite for my project. I have set up the output.assetFileNames
option to categorize assets into subfolders based on their types (css, fonts, img, js), but it's not functioning as anticipated.
Here is my Vite Configuration:
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import autoprefixer from 'autoprefixer';
import imagemin from 'imagemin';
import imageminWebp from 'imagemin-webp';
// Specify the input and output directories for img minify
const inputDir = './src/assets/img';
const outputDir = './dist/assets';
export default defineConfig({
server: {
host: true,
port: 8080,
open: true,
https: false,
proxy: {
'/api': {
target: 'https://jsonplaceholder.typicode.com',
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, ''),
},
},
},
css: {
postcss: {
plugins: [
autoprefixer(), // Add CSS prefixes
],
},
},
build: {
plugins: [
vue(),
autoprefixer(), // Add CSS prefixes
// Minify images
imagemin([`${inputDir}/*.{jpg,png}`], {
destination: outputDir,
plugins: [
imageminWebp({
quality: 75, // Adjust the quality (0 to 100)
}),
],
}),
],
assetsDir: 'assets',
minify: 'terser', // or 'esbuild' for esbuild-based minification
sourcemap: true,
cssCodeSplit: true,
rollupOptions: {
output: {
assetFileNames: ({ name, ext }) => {
// Organize assets based on file type
if (ext === '.css') {
return `assets/css/${name}`;
} else if (ext === '.woff' || ext === '.woff2') {
return `assets/fonts/${name}`;
} else if (ext === '.jpg' || ext === '.webp') {
return `assets/img/${name}`;
} else if (ext === '.js') {
return `assets/js/${name}`;
}
// For other file types, use the default output format with hash
return `assets/${name}`;
},
},
},
},
});
I tried various approaches, but this closely resembles the structure with this configuration
Project Structure:
dist
┣ assets
┃ ┣ arslaner.jpg
┃ ┣ arslaner.webp
┃ ┣ index-gT3gkYz_.js.map
┃ ┣ index.css
┃ ┣ rawert.jpg
┃ ┣ rawert.webp
┃ ┣ SegoeUI-VF.woff
┃ ┗ SegoeUI-VF.woff2
┣ index.html
┗ vite.svg
Expected Output:
dist
┣ assets
┃ ┣ css
┃ ┃ ┗ index.css
┃ ┣ fonts
┃ ┃ ┣ SegoeUI-VF.woff
┃ ┃ ┗ SegoeUI-VF.woff2
┃ ┣ img
┃ ┃ ┣ arslaner.jpg
┃ ┃ ┣ arslaner.webp
┃ ┃ ┣ rawert.jpg
┃ ┃ ┗ rawert.webp
┃ ┗ js
┃ ┃ ┗ index-gT3gkYz_.js.map
┣ index.html
┗ vite.svg
Issue:
Despite setting up the output.assetFileNames
function, the assets are not getting structured into the specified subdirectories. I've double-checked the file extensions, revisited the Vite configuration, and attempted a clean build, but the problem persists.
Your assistance in resolving this matter would be greatly appreciated. If additional information is required, please don't hesitate to ask. Thank you!