> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# 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:

:::info
When using Modern.js [Conventional routing](/guides/basic-features/routes/routes.md#conventional-routing). By default, code splitting is done according to the routing component, so you don't need to do it yourself.
:::

- dynamic `import`
- `React.lazy`
- `loadable`

## Dynamic import

When using dynamic `import()`, the JS modules passed to this API will be bundled as a separate JS file. For example:

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

## React.lazy

The official way provided by React to split component code.

:::caution
`React.lazy` is typically used 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.
:::

```tsx
import React, { Suspense } from 'react';

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

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

For details, see [React lazy](https://react.dev/reference/react/lazy).

## Loadable

In Modern.js, you can use the Loadable API, which is exported from `@modern-js/runtime/loadable`. Here's an example:

```tsx
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>`.

:::info
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](/apis/app/runtime/utility/loadable.md).
