---
sidebar_position: 3
---

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

use dynamic `import()`, the JS modules pass 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 officially way provides by React to split component code.

:::caution
`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.
:::

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