How to import CSS/JS files for Laravel Vite Builds

2.2k Views Asked by At

This is my current Laravel Vite configuration vite.config.js

import { defineConfig } from 'vite'
import laravel from 'laravel-vite-plugin'
import vue from '@vitejs/plugin-vue2'

export default defineConfig({
    plugins: [
        vue(),
        laravel({
            input: ['resources/sass/_top/top.scss'],
            refresh: true
        })
    ],
    server: {
        port: 3500
    },
    resolve: {
        alias: {
            vue: 'vue/dist/vue.esm.js'
        }
    }
})

The input file generates a file at public/build/assets/top.d0g7acf3.css. How do I use this file at my blade file without explicitly using the string d0g7acf3 which changes every build?

Of course this works in my blade file :

<!-- more html codes -->
@vite('build/assets/top.d0d7acf2.css')
<!-- more html codes -->

These don't work:

  • @vite('build/assets/top.css')
  • @vite('resources/sass/_top/top.scss')
1

There are 1 best solutions below

0
Karl Hill On

In Laravel Vite, you can use the @vite directive in your Blade templates to include the generated CSS and JS files. The @vite directive automatically handles the hashed filenames for you.

However, you should not include the file extension when using the @vite directive. So instead of @vite('build/assets/top.css'), you should use @vite('build/assets/top').

Here's how you can include the generated CSS file in your Blade template:

<!-- more html codes -->
@vite('build/assets/top')
<!-- more html codes -->

This will include the correct CSS file, even if the filename changes with each build due to hashing.