Code Splitting

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:

import('./math').then(math => {
  console.log(math.add(16, 26));


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.

import React, { Suspense } from 'react';

const OtherComponent = React.lazy(() => import('./OtherComponent'));
const AnotherComponent = React.lazy(() => import('./AnotherComponent'));

function MyComponent() {
  return (
      <Suspense fallback={<div>Loading...</div>}>
          <OtherComponent />
          <AnotherComponent />

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:

import loadable from '@modern-js/runtime/loadable';

const OtherComponent = loadable(() => import('./OtherComponent'));

function MyComponent() {
  return <OtherComponent />;

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.