【问题标题】:Next Js dynamic imports with no SSR not workingNext 没有 SSR 的 Js 动态导入不起作用
【发布时间】:2021-06-24 18:54:48
【问题描述】:

我正在尝试使用这个 react-carousel-3d 库 https://github.com/suhailsulu/react-carousel-3d,但由于该库不是为支持 SSR 而开发的,因此出现以下错误。

`ReferenceError: window is not defined`
at Object.<anonymous> (C:\Deba\Workspace2021\Nextjs\myportfolio\node_modules\3d-react-carousal\dist\index.js:1:255)

现在我正在尝试使用没有 SSR https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr 的动态导入

const {Carousel} = dynamic(
    () => import('../node_modules/3d-react-carousal/src/index.js'),
    { ssr: false }
  )

我现在遇到以下错误:

./node_modules/3d-react-carousal/src/index.js 189:12
Module parse failed: Unexpected token (189:12)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
     render() {
        return (
             <div className="react-3d-carousel" style={{ height: this.state.height }}>
                 {this.state.slides && this.state.slides.length > 0 &&
                     <div className="slider-container">

有人可以指出我在这里做错了什么或任何关于如何使它工作的想法吗?

【问题讨论】:

    标签: reactjs next.js server-side-rendering


    【解决方案1】:

    不确定是否可以从 node_module 动态加载,如下所示:

    const {Carousel} = dynamic(
        () => import('3d-react-carousal'),
        { ssr: false }
      )
    

    但是你应该能够通过首先创建一个轮播组件来做到这一点,然后像这样动态导入它:

    // create a component named MyCarousel.js in components folder
    import {Carousel} from '3d-react-carousal';
    
    let slides = [
        <img  src="https://picsum.photos/800/300/?random" alt="1" />,
        <img  src="https://picsum.photos/800/301/?random" alt="2" />  ,
        <img  src="https://picsum.photos/800/302/?random" alt="3" />  ,
        <img  src="https://picsum.photos/800/303/?random" alt="4" />  ,
        <img src="https://picsum.photos/800/304/?random" alt="5" />   ];
    
    const MyCarousel = (<Carousel slides={slides} autoplay={true} interval={1000}/>);
    export default MyCarousel;
    
    // then dynamic import it:
    
    const MyCarousel = dynamic(
        () => import('../components/MyCarousel'),
        { ssr: false }
      )
    

    【讨论】:

      猜你喜欢
      • 2021-06-21
      • 2021-09-03
      • 2019-09-16
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      • 1970-01-01
      • 2019-11-14
      相关资源
      最近更新 更多