# @gravity-ui/app-layout 中文文档

规范地址：https://npmcn.com/package/%40gravity-ui/app-layout/

版本：2\.8\.2
npm 元数据更新时间：2026-10-27T09:15:49.457Z
中文译文更新时间：2026-11-16T23:47:18.019Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%40gravity-ui/app-layout
原文对照：https://npmcn.com/package/%40gravity-ui/app-layout/?lang=original
项目主页：https://github.com/gravity-ui/app-layout#readme
源码仓库：https://github.com/gravity-ui/app-layout

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

- 包体积（解压后）：223 kB，132 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- 首次发布：2022-10-25T19:03:18.229Z
- 最新版本发布：2026-10-27T09:15:48.975Z
- 近 30 天下载量：29870（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：33（近 12 个月 9 个）

## 中文简介

## 安装

## 安装

```sh
npm install @gravity-ui/app-layout
```

也可以使用：`pnpm add @gravity-ui/app-layout`、`yarn add @gravity-ui/app-layout`、`bun add @gravity-ui/app-layout`

## README

# @gravity-ui/app-layout ! (简体中文) [![npm package](https://img.shields.io/npm/v/@gravity-ui/app-layout)](https://www.npmjs.com/package/@gravity-ui/app-layout) [![CI](https://img.shields.io/github/actions/workflow/status/gravity-ui/app-layout/.github/workflows/ci.yml?label=CI&logo=github)](https://github.com/gravity-ui/app-layout/actions/workflows/ci.yml?query=branch:main)

## 安装

```shell
npm install --save-dev @gravity-ui/app-layout
```

## 使用量

与 `express`数字 :

```js
import express from 'express';
import {createRenderFunction} from '@gravity-ui/app-layout';

const app = express();

const renderLayout = createRenderFunction();

app.get('/', function (req, res) {
  res.send(
    renderLayout({
      // RenderParams
      title: 'Home page',
      bodyContent: {
        root: 'Hello world!',
      },
    }),
  );
});

app.listen(3000);
```

地点

```typescript
interface RenderParams<Data, Plugins> {
  // Any json compatible data, will be set to window.__DATA__ on the page
  data?: Data;
  // favicon
  icon?: Icon;
  // nonce to be set on the appropriate tags
  nonce?: string;
  // base tag attributes
  base?: Base;

  // common options
  // Page title
  title: string;
  // language of page, will be set to html tag
  lang?: string;
  isMobile?: boolean;

  // html attributes
  htmlAttributes?: string;
  // header tag content
  // meta tags
  meta?: Meta[];
  // link tags
  links?: Link[];
  // script tags
  scripts?: Script[];
  // style tags
  styleSheets?: Stylesheet[];
  // script tags with inlined code
  inlineScripts?: string[];
  // style tags with inlined styles
  inlineStyleSheets?: string[];

  // content of body tag
  bodyContent?: {
    // class name for body tag
    className?: string;
    // body attributes
    attributes?: string;
    // body content before div tag with id root
    beforeRoot?: string;
    // innerHtml content of div tag with id root
    root?: string;
    // body content after div tag with id root
    afterRoot?: string;
  };
  // plugins options
  pluginsOptions?: Partial<PluginsOptions<Plugins>>;
}
```

### 基础

说明 `base` 标签 :

```typescript
interface Base {
  href?: string;
  target?: HTMLBaseElement['target'];
}
```

示例

```js
renderLayout({
  title: 'Home page',
  base: {target: '_top'},
});
```

将作为:

```html
<base target="_top" />
```

### 元数据

说明 `meta` 标签 :

```typescript
interface Meta {
  name: string;
  content: string;
}
```

示例

```js
const meta = [
  {name: 'description', content: 'some text'},
  {name: 'robots', content: 'noindex'},
  {name: 'og:title', content: 'Some title'},
];
```

将作为:

```html
<meta name="description" content="some text" />
<meta name="robots" content="noindex" />
<meta property="og:title" content="Some title" />
```

### 图标

描述页面外观 :

```typescript
interface Icon {
  type?: string;
  sizes?: string;
  href?: string;
}
```

默认值为:

```js
const icon = {
  type: 'image/png',
  sizes: '16x16',
  href: '/favicon.png',
};
```

### 链接

说明 `link` 标签 :

```typescript
interface Link {
  as?: string;
  href: string;
  rel?: string;
  type?: string;
  sizes?: string;
  title?: HTMLLinkElement['title'];
  crossOrigin?: '' | 'anonymous' | 'use-credentials';
}
```

示例

```js
const link = {
  href: 'myFont.woff2',
  rel: 'preload',
  as: 'font',
  type: 'font/woff2',
  crossOrigin: 'anonymous',
};
```

将作为:

```html
<link href="myFont.woff2" rel="preload" as="font" type="font/woff2" crossorigin="anonymous" />
```

### 脚本

描述与预装脚本的链接 :

```typescript
interface Script {
  src: string;
  defer?: boolean;
  async?: boolean;
  crossOrigin?: '' | 'anonymous' | 'use-credentials';
  type?: 'importmap' | 'module' | string;
}
```

示例

```js
const script = {
  src: 'url/to/script',
  defer: true,
  async: false,
  crossOrigin: 'anonymous',
};
```

将作为:

```html
<link href="url/to/script" rel="preload" as="script" crossorigin="anonymous" />

<script src="url/to/script" defer="true" async="false" crossorigin="anonymous" nonce="..."></script>
```

#### 样式表

描述样式的链接 :

```typescript
interface Stylesheet {
  href: string;
}
```

示例

```js
const styleSheet = {
  href: 'url/to/stylesheet',
};
```

将作为:

```html
<link href="url/to/stylesheet" rel="stylesheet" />
```

## 插件

Render功能可以通过插件来扩展. 插件可能会重写定义的用户渲染内容 . 插件是对象 `name` 财务报告和审定财务报表 `apply` 属性 :

```typescript
interface Plugin<Options = any, Name = string> {
  name: Name;
  apply: (params: {
    options: Options | undefined; // passed through `renderLayout` function in `pluginsOptions` parameter.
    commonOptions: CommonOptions;
    renderContent: RenderContent;
    /** @deprecated use `renderContent.helpers` instead */
    utils: RenderHelpers;
  }) => void;
}

interface CommonOptions {
  name: string;
  title: string;
  lang?: string;
  isMobile?: boolean;
}

export interface HeadContent {
  base?: Base;
  scripts: Script[];
  helpers: RenderHelpers;
  links: Link[];
  meta: Meta[];
  styleSheets: Stylesheet[];
  inlineStyleSheets: string[];
  inlineScripts: string[];
  title: string;
}

export interface BodyContent {
  attributes: Attributes;
  beforeRoot: string[];
  root?: string;
  afterRoot: string[];
}

export interface RenderContent extends HeadContent {
  htmlAttributes: Attributes;
  bodyContent: BodyContent;
}

export interface RenderHelpers {
  renderScript(script: Script): string;
  renderInlineScript(content: string): string;
  renderStyle(style: Stylesheet): string;
  renderInlineStyle(content: string): string;
  renderMeta(meta: Meta): string;
  renderLink(link: Link): string;
  attrs(obj: Attributes): string;
}
```

此软件包中有一些插件 :

### 谷歌分析

在页面上添加google分析计数器.

用法 :

```js
import {createRenderFunction, createGoogleAnalyticsPlugin} from '@gravity-ui/app-layout';

const renderLayout = createRenderFunction([createGoogleAnalyticsPlugin()]);

app.get((req, res) => {
  res.send(
    renderLayout({
      title: 'Home page',
      pluginsOptions: {
        googleAnalytics: {
          useBeaconTransport: true, // enables use of navigator.sendBeacon
          counter: {
            id: 'some id',
          },
        },
      },
    }),
  );
});
```

插件选项 :

```typescript
interface GoogleAnalyticsCounter {
  id: string;
}

interface GoogleAnalyticsOptions {
  useBeaconTransport?: boolean;
  counter: GoogleAnalyticsCounter;
}
```

### 扬德克·梅特里卡

在页面上添加 Yandex 度量衡.

用法 :

```js
import {createRenderFunction, createYandexMetrikaPlugin} from '@gravity-ui/app-layout';

const renderLayout = createRenderFunction([createYandexMetrikaPlugin()]);

app.get((req, res) => {
  res.send(
    renderLayout({
      title: 'Home page',
      pluginsOptions: {
        yandexMetrika: {
          counter: {
            id: 123123123,
            defer: true,
            clickmap: true,
            trackLinks: true,
            accurateTrackBounce: true,
          },
        },
      },
    }),
  );
});
```

插件选项 :

```typescript
export type UserParams = {
  [x: string]: boolean | string | number | null | UserParams;
};

export interface MetrikaCounter {
  id: number;
  defer: boolean;
  clickmap: boolean;
  trackLinks: boolean;
  accurateTrackBounce: boolean | number;
  webvisor?: boolean;
  nonce?: string;
  encryptedExperiments?: string;
  triggerEvent?: boolean;
  trackHash?: boolean;
  ecommerce?: boolean | string;
  type?: number;
  userParams?: UserParams;
}

export type MetrikaOptions = {
  src?: string;
  counter: MetrikaCounter | MetrikaCounter[];
};
```

### 版式

从 Webpack 资产列表文件中添加脚本和样式.

用法 :

```js
import {createRenderFunction, createLayoutPlugin} from '@gravity-ui/app-layout';

const renderLayout = createRenderFunction([
  createLayoutPlugin({manifest: 'path/to/assets-manifest.json', publicPath: '/build/'}),
]);

app.get((req, res) => {
  res.send(
    renderLayout({
      title: 'Home page',
      pluginsOptions: {
        layout: {
          name: 'home',
        },
      },
    }),
  );
});
```

插件选项 :

```typescript
export interface LayoutOptions {
  name: string;
  prefix?: string;
}
```

#### 公共路径倒计时

从备份地址装入初始脚本和样式表 `publicPath` 失败.

用法 :

```js
createLayoutPlugin({
  manifest: 'path/to/assets-manifest.json',
  publicPath: 'https://static.example.com/build/',
  publicPathFallbacks: ['https://backup.example.com/build/', '/build/'],
});
```

这些选项也可在以下表格中找到: `createDefaultPlugins({layout: …})`启用布局插件 `pluginsOptions.layout.name`,如上述例子。 选择 `publicPathFallbacks` 或通过 `[]` 保存正常渲染.

您也可以使用回调函数 :

```js
createLayoutPlugin({
  manifest: 'path/to/assets-manifest.json',
  publicPath: 'https://static.example.com/build/',
  publicPathFallbacks: () =>
    location.hostname.endsWith('.example.org')
      ? ['https://backup.example.org/build/', '/build/']
      : ['/build/'],
});
```

该功能运行一次,必须自成一体,不得关闭或进口. 它接收 `{publicPath}`;对于根相对主路径,该值包括 `layout.prefix`返回 `[]` 使用主地址而不重试.

装入器被捆绑和精密化,当应用放出时. 用户调用从编译的服务器代码中序列化 `Function.prototype.toString()`: 重建等转型 `keepNames` 能够注入外部帮助( e)`__name`)在浏览器中找不到。 在您的终端服务器构建中测试回调 。 HTML 解析期间, 如果靴子拖放, 同步注册将恢复脚本标记通过 `document.write`,但受浏览器限制;如果CSP屏蔽了注册脚本,恢复也无济于事.

重试选项 :

```typescript
interface AssetRetryOptions {
  retries?: number; // Additional attempts per address. Default: 0.
  delayMs?: number; // Delay before the first retry, in milliseconds. Default: 500.
  factor?: number; // Multiplier for subsequent retry delays. Default: 2.
  maxDelayMs?: number; // Maximum retry delay, in milliseconds. Default: 3000.
  timeoutMs?: number; // Attempt timeout, in milliseconds. Default: 10000; 0 disables.
}
```

通过这些选项为 `assetRetry` 改为 `createLayoutPlugin`。默认情况下,一个资源错误在不重试同一 URL的情况下切换到下一个地址。 设定 `retries` 以指数延迟的方式进行更多的尝试。 加载器记得最后一个成功的地址并在那里开始后续的脚本,将剩下的地址循环作为备份. 样式表总是从 `publicPath`,然后在配置的顺序中尝试备份地址。 单个失败不会改变首选地址;只有在成功加载后才会改变. 飞行资源保持其候选顺序。 明确 `undefined` 选项值使用默认值.

每个脚本或样式表尝试都有一个 `timeoutMs` 限制(默认为1,000毫秒)。 超时跟装入错误一样遵循同样的重试策略:在尝试时重试当前 URL,然后尝试下一个地址. 设定 `0` 以禁用超时。 加载器会去掉超时出元素并忽略其后回调;去掉一个脚本并不能保证取消其执行.

备份地址必须在同一相对路径上为相同的构建文件服务. 不包括查询参数或基址中的片段. 被添加了倒挂并自动去掉重复地址. 类似路径 `/build/` 相对于页面来源; 明确包含任何应用程序前缀。 允许 CSP 中的备份域并配置 CORS .

正在装入行为 :

-   支助 `defer` 没有脚本 `async` 或者说 `type`样式表 `nonce` 财务报告和审定财务报表 `crossOrigin`其他资源保持正常的渲染。 响应片段的所有管理资产都由靴子后发射的单一内行脚本按头顺序(样式表,然后是脚本)注册;原始脚本标记不渲染出.
-   样式表包含在HTML中,并同时加载,即使JavaScript加载器无法启动. 部分样式的内容在重试时可能可见. 脚本在样式表尝试完成后运行, DOM 已准备好 . `DOMContentLoaded` 并不意味着应用程序已装入完毕.
-   最终失败 `app-layout:asset-load-error` 打开 `window`。事件细节包含 `{type, originalUrl, attempts}` 并被导出 `AssetLoadError` 类型; `attempts` 列出尝试的URL,包括重试。 在装入资源前注册处理器 。 最终样式表加载失败不会阻断脚本; 最终脚本加载失败会阻止加载者的脚本队列 .
-   用于流出时的早期脚本, 使用 `renderScripts(content, scripts, state)`,则 `renderHeadContent(content, state)` 同样的 `state: AssetRenderState = {}` 对于一个 HTML 响应,即使内容被重新生成。 打电话 `renderHeadContent` 每个 HTML 响应一次。 Bootstrap一次被放出;其初始配置适用于整个响应. 直接 `content.helpers` 呼叫生成普通标记而不进行倒置处理.
-   流出时,样式表的 `timeoutMs` 当引用到达 HTML 时开始。 无法找到的已注册样式表链接 `DOMContentLoaded` 被报告为失败,而不阻断脚本.

```ts
import {renderHeadContent, renderScripts, type AssetRenderState} from '@gravity-ui/app-layout';

const state: AssetRenderState = {};
res.write(renderScripts(content, firstScripts, state));
// ... await data and regenerate content if needed.
res.write(renderHeadContent(content, state));
```

懒散块需要单独的配置,例如 `client.publicPathFallback` 内 [应用程序构建器](https://github.com/gravity-ui/app-builder)。配置两个库中的备份地址;不通过全局变量共享后退列表.

### @ gravity-ui/ wiikit (重力- iikit )

添加身体属性.

用法 :

```js
import {createRenderFunction, createUikitPlugin} from '@gravity-ui/app-layout';

const renderLayout = createRenderFunction([createUikitPlugin()]);

app.get((req, res) => {
  res.send(
    renderLayout({
      title: 'Home page',
      pluginsOptions: {
        uikit: {
          theme: 'dark',
          direction: 'ltr',
        },
      },
    }),
  );
});
```

插件选项 :

```typescript
interface UikitPluginOptions {
  theme: string;
  direction?: 'ltr' | 'rtl';
}
```

### 远程版本

向页面添加微前端版本信息.

此插件创建全局 `window.__REMOTE_VERSIONS__` 对象包含提供的微前端版本,可以被模块front或类似的微前端架构所使用,以确定要加载的远程模块的哪些版本.

它可以结合使用 [应用程序构建器](https://github.com/gravity-ui/app-builder?tab=readme-ov-file#module-federation) 编辑 `moduleFederation.remotesRuntimeVersioning` 选项可以自动加载带有相应版本的远程模块.

用法 :

```js
import {createRenderFunction, createRemoteVersionsPlugin} from '@gravity-ui/app-layout';

const renderLayout = createRenderFunction([createRemoteVersionsPlugin()]);

app.get((req, res) => {
  res.send(
    renderLayout({
      title: 'Home page',
      pluginsOptions: {
        remoteVersions: {
          header: '1.2.3',
          footer: '2.1.0',
          sidebar: '0.5.1',
        },
      },
    }),
  );
});
```

插件选项 :

```typescript
type RemoteVersionsPluginOptions = Record<string, string>;
```

### 帮助者

创建所有插件的助手 :

```js
import {createMiddleware, createDefaultPlugins} from '@gravity-ui/app-layout';

const renderLayout = createRenderFunction(
    createDefaultPlugins({layout: {manifest: 'path/to/assets-manifest.json'}})
);

app.get((req, res) => {
    res.send(renderLayout({
        title: 'Home page',
        pluginsOptions: {
            layout: {
                name: 'home'
            },
            googleAnalytics: {
                counter: {...}
            },
            yandexMetrika: {
                counter: {...}
            },
        },
    }));
})
```

## 替代用途

用零件渲染器 `generateRenderContent`, (中文(简体) ), `renderHeadContent`, (中文(简体) ), `renderBodyContent` 通过 html 流线:

```js
import express from 'express';
import htmlescape from 'htmlescape';
import {
  generateRenderContent,
  renderHeadContent,
  renderBodyContent,
  createDefaultPlugins,
} from '@gravity-ui/app-layout';

const app = express();

app.get('/', async function (req, res) {
  res.writeHead(200, {
    'Content-Type': 'text/html',
    'Transfer-Encoding': 'chunked',
  });

  const plugins = createDefaultPlugins({layout: {manifest: 'path/to/assets-manifest.json'}});

  const content = generateRenderContent(plugins, {
    title: 'Home page',
  });

  const {htmlAttributes, helpers, bodyContent} = content;

  res.write(`
        <!DOCTYPE html>
        <html ${helpers.attrs({...htmlAttributes})}>
        <head>
            ${renderHeadContent(content)}
        </head>
        <body ${helpers.attrs(bodyContent.attributes)}>
            ${renderBodyContent(content)}
    `);

  const data = await getUserData();

  res.write(`
            ${content.renderHelpers.renderInlineScript(`
                window.__DATA__ = ${htmlescape(data)};
            `)}
        </body>
        </html>
    `);
  res.end();
});

app.listen(3000);
```

## 常见问题

### @gravity-ui/app-layout 是什么？

安装

### 如何安装 @gravity-ui/app-layout？

在项目目录运行 npm install @gravity-ui/app-layout，或使用 pnpm add / yarn add / bun add。

### @gravity-ui/app-layout 支持 TypeScript 吗？

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

### @gravity-ui/app-layout 支持 ESM 还是 CommonJS？

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

### @gravity-ui/app-layout 可以商用吗？

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

### @gravity-ui/app-layout 的下载量有多少？

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

### @gravity-ui/app-layout 还在维护吗？

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

