Changing Vite Build Directory in Laravel while Maintaining File Names

When working with Laravel and Vite, you might need to customize the vite build output dir for your built assets. By default, Vite places built files in the build directory, but you can configure this to match your project's structure. Ensuring that file names like app.js and app.css are maintained can prevent potential issues caused by Laravel's default behavior of generating random file names. Here’s how to change the build directory for Vite files in a Laravel application while maintaining consistent file names.

Potential Issues with Default Settings

  • Random File Names: Laravel generates random names for assets by default, which can lead to difficulties in maintaining consistent references in your templates.
  • Asset Path Conflicts: If paths are not fully specified, it can cause conflicts and make debugging harder.
  • Template Updates: Existing templates might need to be updated to reference the new file paths correctly.

1. Update vite.config.js

First, update your vite.config.js file to specify the new output directory. Below is a sample configuration that changes the build output directory to statics:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
export default defineConfig({
    plugins: [
        laravel({
            input: ['resources/css/app.css', 'resources/js/app.js'],
            refresh: true,
        }),
    ],
    build: {
        rollupOptions: {
            output: {
                entryFileNames: 'statics/js/[name].js',
                chunkFileNames: 'statics/js/[name].js',
                assetFileNames: 'statics/css/[name].[ext]',
            }
        }
    }
});

2. Configure Laravel to Use the New Directory

Next, ensure Laravel is aware of the new directory structure. Update your views and asset paths as needed. Here’s an example of a Blade template reflecting the new build directory:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    @vite('resources/css/app.css')
</head>
<body>
    <h1>Hello, Laravel with Vite!</h1>
    @vite('resources/js/app.js')
</body>
</html>

3. Run the Build

Run the build process to see your assets being output to the new directory:

npm run build

Conclusion

By following these steps, you've configured Vite to change the build directory for your Laravel application, maintaining the file names app.js and app.css. This customization helps in organizing your assets more effectively, especially in larger projects. Always test your application thoroughly after making configuration changes to ensure all asset paths are correctly resolved.

Happy coding!