---
title: 启用 BFF
---

和之前章节一样，我们同样使用生成器来启用 BFF。

在项目根目录下执行 `pnpm run new` 命令：

```bash
# 启用可选功能
❯ 启用「BFF」功能
  ...

# 请选择 BFF 类型
❯ 函数写法
  框架写法

# 请选择运行时框
❯ Express
  Koa
  Egg
  Nest
```

:::info 注
函数模式与框架模式都是基于 Modern.js 的 BFF 函数的，两种模式的主体都是函数，也都需要运行时框架的支持，这里的提问是为了提供不同的样板文件。更多相关内容可以查看[一体化 BFF 专题](/docs/guides/features/server-side/bff/function)。
:::

我们先选择【 函数写法 】，并选择运行时框架为 Express，项目结构将变成：

```md
.
├── .vscode/
├── api/
│   ├── info/
│   │   └── [type].ts
│   ├── .eslintrc.json
│   ├── _app.ts
│   └── index.ts
├── src/
│   ├── contacts/
│   │   ├── components/
│   │   │   ├── Avatar/
│   │   │   │   ├── index.stories.tsx
│   │   │   │   └── index.tsx
│   │   │   └── Item/
│   │   │       ├── index.test.tsx
│   │   │       └── index.tsx
│   │   ├── styles/
│   │   │   └── utils.css
│   │   ├── App.css
│   │   └── App.tsx
│   ├── landing-page/
│   │   └── pages/
│   │       ├── comments/
│   │       │   └── [commentTitle]/
│   │       │       └── index.tsx
│   │       ├── _app.tsx
│   │       ├── docs.tsx
│   │       └── index.tsx
│   ├── .eslintrc.json
│   └── modern-app-env.d.ts
├── .editorconfig
├── .gitignore
├── .npmrc
├── .nvmrc
├── README.md
├── package.json
├── pnpm-lock.yaml
└── tsconfig.json
```

新增的 `api/` 目录，跟 `src/` 目录一样是源代码目录，目录中有几个示范用法的样板文件

`package.json` 中则会增加 BFF 插件：

```json
+ "@modern-js/plugin-bff"
+ "@modern-js/plugin-express"
+ "express"
```

在函数写法中，BFF 的 API 路由也遵循类似【 约定式路由 】的生成逻辑。

Modern.js Serverless BFF 的默认前缀为 `/api`，例如上述目录结构可以得到两个 API 路由：

`http://localhost:8080/api`

`http://localhost:8080/api/info/:type`

---

> 本小节的代码可以在[这里查看](https://github.com/modern-js-dev/modern-js-examples/tree/main/tutorials/c09/hello-modern-2)。
