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

# Next.js

[next-rspack](https://www.npmjs.com/package/next-rspack) 是一个社区驱动的插件，它允许 Next.js 项目使用 Rspack 作为打包工具（实验性）。

:::tip
查看 [Rspack 加入 Next.js 生态](https://rspack.rs/zh/blog/rspack-next-partner.md) 博客文章了解更多。
:::

## 安装

安装 `next-rspack` 包：


```sh [npm]
npm add next-rspack -D
```

```sh [yarn]
yarn add next-rspack -D
```

```sh [pnpm]
pnpm add next-rspack -D
```

```sh [bun]
bun add next-rspack -D
```

```sh [deno]
deno add npm:next-rspack -D
```

:::tip
如果你使用的 Next.js 版本低于 15.3.0，请先升级到 >= 15.3.0 版本，参考 [Next.js - Upgrading](https://nextjs.org/docs/pages/building-your-application/upgrading)。
:::

## 使用

在项目的 `next.config.mjs` 或 `next.config.ts` 中，对现有配置进行包装：


**next.config.ts**

```ts
import withRspack from 'next-rspack';
import type { NextConfig } from 'next';

const nextConfig: NextConfig = {/* config options here */};

export default withRspack(nextConfig);
```


**next.config.mjs**

```js
import withRspack from 'next-rspack';

/** @type {import('next').NextConfig} */
const nextConfig = {/* config options here */};

export default withRspack(nextConfig);
```


> 示例：[next.js/examples/with-rspack](https://github.com/vercel/next.js/tree/canary/examples/with-rspack)。

## 自定义 Rspack 配置

得益于 Rspack 对 webpack 的兼容性，在使用 `next-rspack` 时，可以沿用与 webpack 相同的方式来自定义配置。

在 `next.config.mjs` 中，通过以下回调函数来修改 Rspack 配置：

```js title="next.config.mjs"
export default {
  webpack: (
    config,
    { buildId, dev, isServer, defaultLoaders, nextRuntime, webpack },
  ) => {
    // 重要：返回修改后的配置
    return config;
  },
};
```

> 更多信息请查看 [Next.js - Custom Webpack Config](https://nextjs.org/docs/app/api-reference/config/next-config-js/webpack)。

## 使用 next-compose-plugins

此外，你可以使用 [next-compose-plugins](https://www.npmjs.com/package/next-compose-plugins) 来快速将 `next-rspack` 与其他 Next.js 插件集成：

```js title="next.config.mjs"
import withPlugins from 'next-compose-plugins';
import withRspack from 'next-rspack';

export default withPlugins([
  [withRspack],
  // 其他插件写在这里
]);
```
