Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Import jQuery on single page with Vite

I am working on a Laravel 11 project with Vite. On one of my adminpages I need jQuery for showing an editor.
I made a js-file for the editor to load:

import "trumbowyg/dist/ui/trumbowyg.min.css";
import "trumbowyg";

$(document).ready(function () {
    $.trumbowyg.svgPath = window.trumbowygSvgPath;
    $("#trumbowyg-editor").trumbowyg();
});

and this is opened here in my bladefile:

        <script type="module">
                window.trumbowygSvgPath = '{{ Vite::asset('resources/images/icons.svg') }}';
        </script>
        <script type="module" src="{{ mix('resources/js/trumbowyg-page.js') }}"></script>

This only works when I import jQuery in the bootstrap.js.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is it possible to import jQuery only for this single site and not globally?

>Solution :

What you can do is installing jQuery using npm install jquery. In your resources folder, you can create a JavaScript file where you import jQuery.

Then you should update your vite.config.js file to add the JavaScript file to the input of the config. If you have added the file to the list you can use @vite('resources/js/file-specific.js'). Now you have only included jQuery on that specific page.

resources/js/page-specific.js

import $ from 'jquery';

// Example usage of jQuery
$(document).ready(function () {
    console.log('jQuery is loaded and ready on this page!');
});

Vite config

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
    plugins: [
        laravel({
            input: [
                'resources/js/app.js',
                'resources/js/page-specific.js', // your page-specific entry point
            ],
            refresh: true,
        }),
    ],
});

Your blade file:

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Your head content -->
    @vite('resources/js/page-specific.js') <!-- Include the specific JS file -->
</head>
<body>
    <!-- Your body content -->

    <h1>This page has jQuery loaded!</h1>
</body>
</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading