# Next.js 实现动态引入，实现对非 SSR 组件的支持

- Link: https://www.ixiqin.com/2022/05/08/next-js-to-realize-dynamic-introduction-implementation-of-ssr-components/
- Published: 2022-05-08T06:00:00+08:00
- Author: 白宦成

文章目录

 [Toggle](https://www.ixiqin.com/2022/05/08/next-js-to-realize-dynamic-introduction-implementation-of-ssr-components/#)

 * [总结](https://www.ixiqin.com/2022/05/08/next-js-to-realize-dynamic-introduction-implementation-of-ssr-components/#%e6%80%bb%e7%bb%93)
 * [参考阅读](https://www.ixiqin.com/2022/05/08/next-js-to-realize-dynamic-introduction-implementation-of-ssr-components/#%e5%8f%82%e8%80%83%e9%98%85%e8%af%bb)

在使用 Next.js 进行开发的时候，会遇到某些组件是不提供 SSR 支持的（很正常，毕竟 SSR
是一个相对比较小众的应用场景。此外，某些组件会依赖浏览器环境的上下文），在这种情况
下，我们需要一种方式来实现对非 SSR 组件的支持。

一般而言， 有两种方式，一种是使用 `useEffects` 来控制组件的载入，从而实现只在客户
端层面加载组件，服务端渲染的时候就不再加载该组件。

另外一种方式是可以考虑借助于 Next.js 自带的 **Dynamic Import** 的特性，来完成组件
的引入。

在使用层面比较简单，引入组件的方式从直接引入改为最外层套一层 dynamic 函数即可

    ```javascript
    import dynamic from 'next/dynamic'

    const DynamicComponentWithNoSSR = dynamic(
      () => import('../components/hello3'),
      { ssr: false }
    )

    function Home() {
      return (
        <div>
          <Header />
          <DynamicComponentWithNoSSR />
          <p>HOME PAGE is here!</p>
        </div>
      )
    }

    export default Home
    Code language: JavaScript (javascript)
    ```

## 总结

这个问题的解决让我再次激起了对于 Next.js 的兴趣。过去因为不确定如何解决在浏览器和
客户端环境下的问题，对于 Next.js 有些畏难；如今问题已解决，可以继续放心的使用 Next.
js 了。

## 参考阅读

[https://nextjs.org/docs/advanced-features/dynamic-import](https://nextjs.org/docs/advanced-features/dynamic-import)
