# @dudousxd/nestjs-inertia 中文文档

规范地址：https://npmcn.com/package/%40dudousxd/nestjs-inertia/

版本：3\.0\.1
npm 元数据更新时间：2026-11-12T05:45:50.406Z
中文译文更新时间：2026-11-13T00:05:22.101Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40dudousxd/nestjs-inertia
原文对照：https://npmcn.com/package/%40dudousxd/nestjs-inertia/?lang=original
项目主页：https://davidecarvalho.github.io/aviary/docs/inertia
源码仓库：https://github.com/DavideCarvalho/nestjs-inertia

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：841 kB，13 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=24
- 运行依赖：1 个
- peer 依赖：ejs \>=3\.1\.0，pug \>=3\.0\.0，rxjs \>=7\.0\.0，express \>=4\.0\.0，fastify \>=4\.0\.0，liquidjs \>=10\.0\.0，handlebars \>=4\.7\.0，@nestjs/core \>=10\.0\.0，cookie-parser \>=1\.4\.0，@nestjs/common \>=10\.0\.0，@types/express \>=4\.0\.0，@fastify/cookie \>=9\.0\.0，reflect-metadata \>=0\.1\.13，@nestjs/platform-fastify \>=10\.0\.0
- 首次发布：2026-05-23T18:41:58.824Z
- 最新版本发布：2026-11-12T05:45:50.010Z
- 近 30 天下载量：2796（2026-10-13 至 2026-11-11，npm 官方下载统计）
- 已发布版本数：33（近 12 个月 33 个）

## 中文简介

雀巢JS的Inertia.js适配器——核心协议和模块.

## 安装

```sh
npm install @dudousxd/nestjs-inertia
```

也可以使用：`pnpm add @dudousxd/nestjs-inertia`、`yarn add @dudousxd/nestjs-inertia`、`bun add @dudousxd/nestjs-inertia`

## README

# @dudousxd/nestjs-inertia (英语)

> Inertia.js v3 雀巢JS的适配器 — Express + fastify,多应用程序通过 `forFeature`,4个模板引擎,CSRF保护,完全Inertia v3协议等同.

[![npm](https://img.shields.io/npm/v/@dudousxd/nestjs-inertia.svg)](https://npmjs.com/package/@dudousxd/nestjs-inertia) [![license](https://img.shields.io/npm/l/@dudousxd/nestjs-inertia.svg)](https://github.com/DavideCarvalho/nestjs-inertia/blob/main/LICENSE)

## 安装

```bash
pnpm add @dudousxd/nestjs-inertia

# Pick your HTTP platform
pnpm add express @types/express          # Express adapter (default)
# OR
pnpm add fastify @nestjs/platform-fastify @fastify/cookie  # Fastify adapter
```

## 快开始

```ts
// app.module.ts
import { Module } from '@nestjs/common';
import { InertiaModule } from '@dudousxd/nestjs-inertia';

@Module({
  imports: [
    InertiaModule.forRoot({
      version: () => process.env.ASSET_VERSION ?? 'dev',
      rootView: 'inertia/root.html',
      share: async (req) => ({ auth: req.user ?? null }),
    }),
  ],
})
export class AppModule {}
```

`inertia/root.html`数字 :

```html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>My App</title>
  @inertiaHead
  @vite('app/client.tsx')
  @viteRefresh
</head>
<body>
  @inertia
</body>
</html>
```

## 主计长

两种等同模式共存:

```ts
import { Controller, Get, Req } from '@nestjs/common';
import { Inertia } from '@dudousxd/nestjs-inertia';
import type { Request } from 'express';

@Controller()
export class HomeController {
  // Decorator pattern (idiomatic for new code)
  @Get('/')
  @Inertia('Home')
  show() {
    return { hello: 'world' };
  }

  // Imperative pattern (use when you need fine control)
  @Get('/crew')
  async list(@Req() req: Request) {
    await req.inertia
      .share({ flash: req.session?.flash ?? {} })
      .render('Crew', { crew: await this.svc.list() });
  }
}
```

## Async 配置

```ts
InertiaModule.forRootAsync({
  imports: [ConfigModule],
  inject: [ConfigService],
  useFactory: (cfg: ConfigService) => ({
    version: cfg.get('ASSET_VERSION'),
    rootView: 'inertia/root.html',
  }),
});
```

三种途径: `useFactory + inject` (最常见的), `useClass`, (中文(简体) ), `useExisting`。 。 。 .

## 多应用程序 `forFeature`

在同一 NestJS 进程中主机两个或两个以上Inertia apps——每个都有自己的Vite条目, shell,版本,共享,SSR捆绑. 用于管理面板,多租户白标签,或前端堆栈之间的迁移.

```ts
@Module({
  imports: [
    InertiaModule.forRoot({                  // main app
      vite: { entry: 'app/client.tsx' },
      rootView: 'inertia/root.html',
      share: req => ({ auth: req.user }),
    }),
    InertiaModule.forFeature({               // admin app
      scope: 'admin',
      vite: { entry: 'admin/client.tsx' },
      rootView: 'inertia/admin-root.html',
      share: req => ({ admin: req.adminContext }),
    }),
  ],
})
export class AppModule {}
```

每个控制器/方法选择范围 `@UseInertia('scope')`数字 :

```ts
@Controller('admin')
@UseInertia('admin')
export class AdminDashboardController {
  @Get('/')
  @Inertia('AdminDashboard')
  show() { return { stats: ... }; }
}
```

`forFeatureAsync` 工作与 `forRootAsync` (使用Factory/useClass/useExting). 保留范围: `'default'` 属于 `forRoot()`。 。 。 .

## 模板引擎

`rootView` 接受 `.html` (拥有解析器)加 `.hbs` 编号 : `.ejs` 编号 : `.pug` 编号 : `.liquid` 如果安装了引擎包:

```bash
pnpm add handlebars                    # or: ejs, pug, liquidjs
```

```ts
InertiaModule.forRoot({
  rootView: 'inertia/root.hbs',         // auto-detects Handlebars
});
```

每个引擎看到本地 `{ page, inertia, inertiaHead, vite, viteRefresh, asset }`. 使用引擎本身的逃生规则(例如, `{{{inertia}}}` 手帕的三重出击, `<%- inertia %>` 在EJS中, `!= inertia` (原始内容存档于2013-10-12). In Pug. 这个 `@inertia`编号 :`@inertiaHead`编号 :`@vite`编号 :`@viteRefresh`编号 :`@asset` 指令也会在引擎的输出,根视图和部分/包含相同的情况下被扩展出,这样可以混合并匹配. JSON页、SSR标记和任何打印自 `page` 因此,页面数据从不被视为指令.

## 中国证监会

```ts
import { CsrfCookieInterceptor, CsrfGuard } from '@dudousxd/nestjs-inertia';

// Global cookie writer
app.useGlobalInterceptors(new CsrfCookieInterceptor({ secret: process.env.CSRF_SECRET }));

// Per-route validation
@UseGuards(new CsrfGuard({ secret: process.env.CSRF_SECRET }))
@Post('/profile')
async update() { ... }
```

Cookie 名称 `XSRF-TOKEN`,页眉名称 `X-XSRF-TOKEN` 两者都符合Inertia客户协议. 通过HMAC-SHA256签署. 要求数 `cookie-parser` (执行)或 `@fastify/cookie` (快活地)作为同级Dep.

## 快捷化

```ts
import { FastifyAdapter } from '@nestjs/platform-fastify';

const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
```

与"快递"(Express)的功能完全等同:中件,装饰器,所有截取器,卫所,滤取器,外壳指令,SSR,FlashStore. `request.inertia` 被电线通过 `decorateRequest` + 键 `onRequest` 当检测到快取Adapter时自动钩入.

## 道具标记

```ts
import { Inertia } from '@dudousxd/nestjs-inertia';

return {
  user: Inertia.always(() => currentUser()),
  stats: Inertia.optional(() => heavyStatsCalculation()),
  activity: Inertia.defer(() => activityFeed(), 'secondary'),
  rows: Inertia.merge(() => paginated(p), { matchOn: 'id', deep: false }),
  csrfToken: Inertia.once(() => generateToken()),
};
```

-   `always` ——解决每道曲折(包括部分重载)
-   `optional` - 只有在列入清单时才能解决 `X-Inertia-Partial-Data`
-   `defer` ——列于 `page.deferredProps`; 客户端 v2 发送后续请求
-   `merge` ——解决+标记作为合并目标(客户附件/替换)
-   `once` ——决定首次访问,缓存至 `X-Inertia-Reset-Once` 列出密钥

## 自动包含的基础设施

`forRoot()` 安装 :

-   `InertiaMiddleware` (执行)或 `FastifyInertiaPlugin` \[快活地\] - `req.inertia` 随处可见
-   `MethodSpoofMiddleware` (POST + 多部分 + `_method=PUT/PATCH/DELETE`(中文(简体) )
-   `RedirectInterceptor` 根据PUT/PATCH/DELETE Inertia的请求升级(302 – 303)
-   `InertiaRenderInterceptor` (手执 `@Inertia('Page')` 装饰)
-   `InertiaScopeSwitcherInterceptor` (手执 `@UseInertia('scope')`(中文(简体) )

通过旋钮禁用 :

```ts
InertiaModule.forRoot({
  methodSpoofing: false,
  autoUpgrade303: false,
});
```

## 专用公用事业

```ts
import { ErrorBagInterceptor } from '@dudousxd/nestjs-inertia';

// Error bag interceptor — opt-in per route
@UseInterceptors(ErrorBagInterceptor)
```

> Auth- reirect 守护器和未找到的过滤器不是运出输出 —— 沿着 [直接认证](https://github.com/dudousxd/nestjs-inertia) 和未找到的食谱.

## FlashStore (误差)

NestJS没有自己的会话. 插入适配器 :

```ts
import type { FlashStore } from '@dudousxd/nestjs-inertia';

class ExpressSessionFlashStore implements FlashStore {
  read(req) {
    return (req as Request).session?.flash?.errors ?? {};
  }
}

InertiaModule.forRoot({
  flashStore: new ExpressSessionFlashStore(),
});
```

## 安全部门改革

```ts
InertiaModule.forRoot({
  ssr: {
    enabled: process.env.NODE_ENV === 'production',
    bundlePath: 'dist/inertia/ssr/ssr.mjs',
    throwOnError: false,
  },
});
```

Bundle 必须导出 `default { render(page) }` 或名称 `render(page)` 返回时 `{ head: string[], body: string }`。 。 。 .

## 在服务器捆绑中生成的文件

只有您的服务器将导入文件捆绑到生成的文件中,才能复制到 `nest-cli.json`数字 :

```json
{
  "compilerOptions": {
    "assets": [".nestjs-inertia/**/*"],
    "watchAssets": true
  }
}
```

## 协议对等

完整Inertia协议:X-Inertia头,版本不匹配(409 + X-Inertia-Location,仅取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取.

## 配套包(计划)

-   `@dudousxd/nestjs-inertia-vite` - Vite dev/建设助手(B计划)
-   `@dudousxd/nestjs-inertia-testing` —— 说 `expectInertia(res)` 火柴(B计划)
-   `@dudousxd/nestjs-inertia-codegen` ——打出页数(计划C)
-   `@dudousxd/nestjs-inertia-client` ——图约式打入的REST + TanStack 查询(计划 D)
-   实例+文件网站+CI工作流程(计划E)

见 [`docs/design.md`](https://npmcn.com/package/docs/design.md) 完全设计.

## 许可证

麻省理工学院

## 常见问题

### @dudousxd/nestjs-inertia 是什么？

雀巢JS的Inertia\.js适配器——核心协议和模块\.

### 如何安装 @dudousxd/nestjs-inertia？

在项目目录运行 npm install @dudousxd/nestjs-inertia，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：rxjs（\>=7\.0\.0）、@nestjs/core（\>=10\.0\.0）、@nestjs/common（\>=10\.0\.0）、reflect-metadata（\>=0\.1\.13）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @dudousxd/nestjs-inertia 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @dudousxd/nestjs-inertia 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @dudousxd/nestjs-inertia 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=24。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @dudousxd/nestjs-inertia 可以商用吗？

@dudousxd/nestjs-inertia 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @dudousxd/nestjs-inertia 的下载量有多少？

根据 npm 官方下载统计，@dudousxd/nestjs-inertia 在 2026/10/13 – 2026/11/11 这 30 天内被下载 2,796 次，日均约 93 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @dudousxd/nestjs-inertia 还在维护吗？

最新版本 3\.0\.1 发布于 2026/11/12（1 天前）；至今共发布 33 个版本，其中过去 12 个月发布了 33 个；首次发布于 2026/05/24。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

