Search code examples
jqueryreactjsnext.jsowl-carousel-2

Use Owl Carousel 2 with next.js and react


I want to use jQuery owl carousel with my next js react app. I dont want to use npm package react-owl-carousel only owl-carousel and jquery plugin.

I use lazy load with next.js dynamic and put the following code in my Webpack config:

import dynamic from 'next/dynamic';
const Slider = dynamic(() => import('...'), {
  ssr: false,
});

Webpack config:

config.plugins.push(new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery',
  'window.jQuery': 'jquery',
}));

Slider component:

import 'owl.carousel';
import 'owl.carousel/dist/assets/owl.carousel.css';

When I use $('element').owlCarousel(...), I got the following error:

TypeError: this.owl.owlCarousel is not a function


Solution

  • after checking the bundle file i find that webpack pass another jQuery instance to owl.carousel file

    here is webpack bundle code

    __webpack_require__(/*! jquery */ "../../node_modules/owl.carousel/node_modules/jquery/dist/jquery.js")
    

    as you can see jQuery pass to plugin from node_modules/owl.carousel/node_modules/jquery/dist/jquery.js instead of node_modules/jquery/dist/jquery.js

    i fixed issue by deleting node_modules/owl.carousel/node_modules

    after that webpack pass node_modules/jquery/dist/jquery.js as jquery instance