skip to Main Content

I use vite to build this project.
when I use owl-carousel from node_modules it works in development mode but after build, the carousel stops working and gets this error

Uncaught TypeError: Cannot read properties of undefined (reading 'fn')
    at index.781bd673.js:4:36786
    at index.781bd673.js:4:37392

so I used it from CDN.

<script type="module">
  // CDN --> working after build 
  // import 'https://code.jquery.com/jquery-3.2.1.slim.min.js';
  // import 'https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js';

  // node_modules --> not working after build
  import './node_modules/jquery/dist/jquery.slim.min.js';
  import './node_modules/owl.carousel/dist/owl.carousel.min.js';

  // customize owl carousel
  import './src/js/owl-carousel.js';
</script>

How to use it from node_modules without that error??

2

Answers


  1. Chosen as BEST ANSWER

    export jQuery globally

    // jquery.js file 
    
    import $ from 'jquery'; // from node_modules
    window.jQuery = $;
    export default $;
    

    and import it in owl-carousel.js

    // owl-carousel.js file
    
    import $ from './jquery.js';
    import 'owl.carousel'; // from node_modules
    
    $(document).ready(function () {
      $('.owl-carousel').owlCarousel({
        loop: true,
        margin: 20,
        autoplay: true,
        responsive: {
          0: {
            items: 1,
          },
          600: {
            items: 2,
          },
          1000: {
            items: 3,
          },
        },
      });
    });
    

  2. The below answer from @Asmaa Mahmoud did not work for me. Below is my solution. I hope this will help someone else struggling with the same issue.

    vite.config.js file:

    import { defineConfig } from 'vite';
    import inject from '@rollup/plugin-inject';
    import htmlPurge from 'vite-plugin-purgecss';
    
    export default defineConfig({
      plugins: [
        inject({
          $: 'jquery',
          jQuery: 'jquery',
          'window.jQuery': 'jquery',
        }),
        htmlPurge(),
      ],
      css: {
        devSourcemap: true,
      },
    });
    

    app.js file:

    import './app.scss';
    import 'owl.carousel/dist/assets/owl.carousel.css';
    import $ from 'jquery';
    import 'lazysizes';
    import 'owl.carousel';
    
    $(function(){
      $('.owl-carousel').owlCarousel({});
    });
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search