Search code examples
laravelnpmlaravel-bladevite

How do I use Vite to build asset file that I can reference in the <head> of my pages?


I'm very confused about how I should use Vite. While developing there are no problems but when I want to build my assets files I have no idea what's going on anymore. I'm used to the days of webpack where all of the assets files (.scss and .js) were bundled up and outputted as app.css and app.js. I'm not sure how I should configure Vite to achieve something similair or if I should even try to.

I have been trying to write something like the following:

    @if(app()->environment('local'))
        @vite(['resources/sass/app.scss', 'resources/js/app.js'])
    @else
        <link rel="stylesheet" href="/assets/stylesheet.css">
        <script src="/assets/app.js"></script>
    @endif

My thought process was basically when the application is not on local it uses the built assets files and during development it uses the @vite[ ... ] statement.

I have the feeling that my approach is not the way Vite should be used but I'm completely lost on how it should be approached. Can someone educate me when it comes to using Vite?


Solution

  • I am not sure why you are using another approach when on production. The documentation is very clear:

    With your Vite entry points configured, you only need reference them in a @vite() Blade directive that you add to the <head> of your application's root template. The @vite directive will automatically detect the Vite development server and inject the Vite client to enable Hot Module Replacement. In build mode, the directive will load your compiled and versioned assets, including any imported CSS.

    So, you have to always use:

    @vite(['resources/sass/app.scss', 'resources/js/app.js'])
    

    It will automatically output <link> and <script> when needed. You do not have to do anything else.