javascript Nextjs中组件客户端渲染的模块负载优化

bxgwgixi  于 5个月前  发布在  Java
关注(0)|答案(1)|浏览(88)

在Nextjs应用程序中,当页面的多个组件使用同一个包时,您可能会期望公共包默认情况下只加载一次,但当组件在客户端渲染时情况并非如此,从而在很大程度上增加了页面大小。下面是一个用例,其中显示了相同的情况。
我有4个组件“Chart 1”,“Chart 2”,“Chart 3”,“Chart 4”与使用'react-plotly.js'包的情节完全相同的代码。当这些组件加载时ssr设置为false,每个组件中的'react-plotly.js'包为每个模块加载。网络数据显示加载了4次5.4MB-每个组件一次。但是当我加载'react-plotly.js' in _app.js并将其作为Context传递,则只有1次5.4MB的加载对应于第一次加载。想要检查Nextjs是否进行了任何优化,以避免在ssr为false时在整个应用程序中加载冗余包?是否有方法强制此优化?
下面是页面代码

import dynamic from "next/dynamic";

const Chart1 = dynamic(() => import('@/components/scheduling/Chart1'), {
  ssr: false,
});

const Chart2 = dynamic(() => import('@/components/scheduling/Chart2'), {
  ssr: false,
});

const Chart3 = dynamic(() => import('@/components/scheduling/Chart3'), {
  ssr: false,
});

const Chart4 = dynamic(() => import('@/components/scheduling/Chart4'), {
  ssr: false,
});

export default function scheduling() {

  return(
    <div>
      <Chart1 />
      <Chart2 />
      <Chart3 />
      <Chart4 />
    </div>
  )
}

字符串
下面是组件代码

import Plot from "react-plotly.js"

import { PlotlyContext } from "@/pages/_app"
import { useContext } from "react"

export default function Chart1() {

  // const Plot = useContext(PlotlyContext)

  return(
    <Plot
      data={[
        {
          x: [7, 2, 3],
          y: [2, 6, 3],
          type: 'scatter',
          mode: 'lines+markers',
          marker: {color: 'red'},
        },
        {type: 'bar', x: [1, 2, 3], y: [2, 5, 3]},
      ]}
      layout={ {width: 320, height: 240, title: 'Chart 1'} }
    />
  )
}

yeotifhr

yeotifhr1#

仅在开发模式下运行时是这种情况,而不是在构建生产模式之后。

相关问题