import js in laravel 10, variable is not defined, for splide js

73 Views Asked by At

I'm using Laravel 10. In my app.js, I import the splide moduel

import '@splidejs/splide/dist/js/splide'
import '@splidejs/splide/dist/css/themes/splide-default.min.css'

However, when I want to use it in my blade,

    <script type="module">
        new Splide( '.splide' ).mount();
    </script>

or

    <script>
        new Splide( '.splide' ).mount();
    </script>

In the console, it shows (index):1197 Uncaught ReferenceError: Splide is not defined

But when I use CDN link in my blade,

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@splidejs/[email protected]/dist/css/splide.min.css">
<script src="https://cdn.jsdelivr.net/npm/@splidejs/[email protected]/dist/js/splide.min.js"></script>

It works.

It looks like that when I import js in app.js, the Splide is not created as a global variable. However, there is no such problem when I use CDN link. I'd like to know, somebody can help me to expliain this problem.

Is it resolvable?

I have the same situation for jquery. When I use import jquery in app.js, there is always an error about jQuery is not defined.

1

There are 1 best solutions below

0
zurdo On

The new Splide() does not work because it cannot find the source. Assuming you've already installed splide via npm, this should be easy.

This is supposed to be in the resources/css/app.css, and not in app.js.

@import '@splidejs/splide/dist/css/themes/splide-default.min.css'

Then in resources/js/app.js, you can import the js file.

import Splide from '@splidejs/splide/dist/js/splide';
new Splide('.splide').mount();

The CDN work because the source is linked directly. While in the npm method, plugins are saved to your project folder. Check out node_modules folder, and you will see the packages you installed. Frameworks usually have their own way of adding links and importing files within the directory. So, make sure to look up how it works, like Laravel in this case.

Reference: