Ligonsker's avatar

How do I add a JS script file to my blade with Vite?

Hi

I created a file at /resources/js/my-script.js

I'm completely new to Vite, how can I make this file work on one of my Blade files?

Do I first need to add it to the main app.js somehow and rebuild and then it will be visible? But how exactly?

** Update: I made it work by importing the JS file inside the app.js:

import './my-script.js';

But does it mean I have to import each and every JS file manually? Or there is a better way to import all the JS files that I place in the resources/js/ directory (And is it a good practice?)

Thanks

1 like
2 replies
vincent15000's avatar

In the vite.config.js file, you have this basic content.

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import tailwindcss from '@tailwindcss/vite';

export default defineConfig({
    plugins: [
        laravel({
            input: ['resources/css/app.css', 'resources/js/app.js', 'resources/js/another_js_file.js', ...], // HERE
            refresh: true,
        }),
        tailwindcss(),
    ],
});

If you need to add more JS files, just add them to the table (value of the input parameter for the laravel function).

You can also import your other script inside the app.js file (like you showed in your post), this way you don't have to declare it inside the vite.config.js file.

martinbean's avatar

@ligonsker You use Vite to bundle multiple scripts into one (an entry point), and you then include the entry point in your Blade layout.

There’s no point using Vite to bundle assets only to then try and import them individually any way.

1 like

Please or to participate in this conversation.