wtsuport
wtsuport

Reputation: 425

How import own js file into vite?

I use Laravel with Vite and I want to add file with Vanillia JS code. Before I used mix and I have never use Vite before. I tryed add this code into file vite.config.js like below example:

laravel({
    input: [
        'resources/sass/app.scss',
        'resources/js/app.js',
        'resources/js/test.js', //this is my code
    ],
    refresh: true,
}),

but it doesn't work. I need to add one library and code with config that. Could you help me?

Upvotes: 17

Views: 32665

Answers (3)

Caro Pérez
Caro Pérez

Reputation: 538

IN LARAVEL 10

main.blade.php:

<head>
    @vite(["resources/js/app.js"])
</head>

IN TERMINAL:

npm install

npm run dev

OPEN OTHER TERMNAL AT THE SAME TIME

php artisan serve

GO TO SERVE PAGE SOMETHIG LIKE http://127.0.0.1:8000

thanks Fguzman

Upvotes: -2

Mario Ariyanto
Mario Ariyanto

Reputation: 326

This is applicable for your own created js files and node modules library js files

You need to both declare it in vite.config.js and initial HTML file (app.blade.php / welcome.blade.php)

In vite.config.js

export default defineConfig({
    plugins: [
        laravel({
            input: [
                'resources/css/app.css',
                'resources/js/app.js',
                'resources/js/test.js', //your custom js
                'node_modules/flowbite/dist/flowbite.js', //node modules js
                'node_modules/flowbite/dist/datepicker.js'
            ],
            refresh: true,
        }),
    ],
});  

In HTML.blade.php

<head>
     @vite(['resources/css/app.css', 'resources/js/app.js',         
     'resources/js/test.js',node_modules/flowbite/dist/flowbite.js' 
     ,'node_modules/flowbite/dist/datepicker.js'])

</head>

P.S: I am using Flowbite plugin as an example here

Upvotes: 9

John Magnolia
John Magnolia

Reputation: 16823

Use the @vite('resources/js/test.js') directive: https://legacy.laravel-vite.dev/guide/usage.html#vite

    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    
        <title>Laravel</title>
        @client
        @vite('main')
        @vite('resources/js/some-script.js')
        <!-- 
        In development:
            <script type="module" src="http://localhost:3000/@vite/client"></script>
            <script type="module" src="http://localhost:3000/resources/scripts/main.ts"></script>
            <script type="module" src="http://localhost:3000/resources/js/some-script.js"></script>
        In production:
            <script type="module" src="http://laravel.local/build/assets/main.66e83946.js"></script>
            <script type="module" src="http://laravel.local/build/assets/some-script.6d3515d2.js"></script>
        -->
    </head>

Upvotes: 4

Related Questions