繁体   English   中英

在 next.js 中使用 Owl Carousel 2 并做出反应

[英]Use Owl Carousel 2 with next.js and react

我想在我的下一个 js react 应用程序中使用 jQuery owl carousel。 我不想只使用 npm 包react-owl-carousel owl-carouseljquery插件。

我在 next.js dynamic使用延迟加载,并将以下代码放入我的 Webpack 配置中:

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

网络包配置:

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

滑块组件:

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

当我使用$('element').owlCarousel(...) ,出现以下错误:

类型错误:this.owl.owlCarousel 不是函数

检查捆绑文件后,我发现 webpack 将另一个 jQuery 实例传递给 owl.carousel 文件

这是 webpack 捆绑代码

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

正如你所看到的,jQuery 从node_modules/owl.carousel/node_modules/jquery/dist/jquery.js而不是node_modules/jquery/dist/jquery.js传递给插件

我通过删除node_modules/owl.carousel/node_modules解决了问题

在 webpack 传递node_modules/jquery/dist/jquery.js作为 jquery 实例之后

  1. 在 next.js 项目根目录下的 next.config.js 文件中通过 jQuery 和 webpack 注入全局窗口

     module.exports = { webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => { // Note: we provide webpack above so you should not `require` it // Perform customizations to webpack config config.plugins.push( new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery" }) ); // Important: return the modified config return config; }
  2. 使用react-owl-carousel组件的滑块组件

     import OwlCarousel from "react-owl-carousel"; export default function MySlider({ sliders }) { return ( <section> <OwlCarousel loop={true} items={1} responsiveRefreshRate={0} autoplay={true} autoplayTimeout={7000} autoplayHoverPause={true} nav={true} navText={[ "<i class='icon-arrow-prev'></i>", "<i class='icon-arrow-next'></i>" ]} dots={false} margin={20} > <div class="item"></div> <div class="item"></div> </OwlCarousel> </section> ); }
  3. 导入组件并在您的父组件上使用。 请注意,您必须使用ssr:false选项。 Next.js 文档推荐它

    const MySlider = dynamic( () => import("./Myslider"), // No need for SSR, when the module includes a library that only works in the // browser. { ssr: false } );

快乐编码。

在 next.config.js 中:

const webpack = require('webpack');
module.exports = {
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
config.plugins.push(new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery'
    }))
return config;
}}

在您的组件中:

import "owl.carousel/dist/assets/owl.carousel.css";
import "owl.carousel/dist/assets/owl.theme.default.css";
const OwlCarousel = dynamic(import("react-owl-carousel"), {ssr: false});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM