Code splitting is a common way to optimize frontend resource loading. This article will introduce the three types of code splitting supported by Modern.js:
When using Modern.js Conventional routing. By default, code splitting is done according to the routing component, so you don't need to do it yourself.
import
React.lazy
loadable
use dynamic import()
, the JS modules pass to this API will be bundled as a separate JS file, for example:
The officially way provides by React to split component code.
React.lazy
is typically used in together with <Suspense>
, hence it is only available in CSR or React 18 Streaming SSR.
For projects that use Traditional SSR(renderToString), React.lazy
is not supported. Please use the Loadable API instead.
For details, see React lazy.
In Modern.js, you can use the Loadable API, which is exported from @modern-js/runtime/loadable
. Here's an example:
With the out-of-the-box support of loadable
in SSR by Modern.js, you no longer need to add Babel plugins or inject scripts into HTML during SSR.
However, it's important to note that any Loadable API in SSR does not support the use of <Suspense>
.
If you want to use <Suspense>
in CSR projects with React 17 and below, you can substitute React.lazy
with loadable.lazy
.
For details, see Loadable API.