# @element-hq/web-shared-components 中文文档

规范地址：https://npmcn.com/package/%40element-hq/web-shared-components/

版本：0\.2\.3
npm 元数据更新时间：2026-11-03T13:35:53.640Z
中文译文更新时间：2026-11-14T00:52:11.542Z
软件包许可：未声明

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

原始 npm 页面：https://www.npmjs.com/package/%40element-hq/web-shared-components
原文对照：https://npmcn.com/package/%40element-hq/web-shared-components/?lang=original
源码仓库：https://github.com/element-hq/element-web

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

- 包体积（解压后）：5.7 MB，758 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=20\.0\.0
- 运行依赖：23 个
- peer 依赖：react ^19\.0\.0，react-dom ^19\.0\.0，@vector-im/compound-web ^8\.3\.5 \|\| ^9\.0\.0 \|\| ^10\.0\.0
- 首次发布：2025-10-10T10:28:57.198Z
- 最新版本发布：2026-11-03T13:35:53.147Z
- 近 30 天下载量：2659（2026-10-14 至 2026-11-12，npm 官方下载统计）
- 已发布版本数：21（近 12 个月 14 个）

## 中文简介

元素共享组件

## 安装

```sh
npm install @element-hq/web-shared-components
```

也可以使用：`pnpm add @element-hq/web-shared-components`、`yarn add @element-hq/web-shared-components`、`bun add @element-hq/web-shared-components`

## README

# @element-hq/web-shared-组件

[在线故事书](https://shared-components-storybook.element.dev/)

Element Web, Aurora, Element 共享反应组件库 模块... 这个软件包提供建在顶端的有意见的UI组件 [复合设计系统](https://compound.element.io/) 财务报告和审定财务报表 [化合物 网页](https://github.com/element-hq/compound-web)这不是设计系统 本身,而是一组更大的组件.

## 在新项目中安装

当将此库添加到新项目时, 以及安装 `@element-hq/web-shared-components` 作为常态,您还需要添加 [复合网络](https://github.com/element-hq/compound-web) 作为对等点 依赖性 :

```bash
pnpm add @element-hq/web-shared-components
pnpm add @vector-im/compound-web
```

(这避免了问题,我们最终会遇到不同版本的复合网络) 顶级项目和网络共享组件).

## 使用量

### 基本导入

JavaScript和CSS都可以导入如下:

```javascript
import { RoomListHeaderView, useViewModel } from "@element-hq/web-shared-components";
import "@element-hq/web-shared-components/dist/element-web-shared-components.css";
```

或 CSS 文件内 :

```css
@import url("@element-hq/web-shared-components");
```

### 子路径导入

正在浏览器 DOM 外运行的呼叫者( 例如 在内) `AudioWorkletGlobalScope` 或工人)可以拉入小独立 `numbers` 没有工具捆绑 装入包件的其余部分,由包件转运进口, dnd-kit, 以及其他触及的代码 `window` 编号 : `document`数字 :

```javascript
import { percentageOf, percentageWithin } from "@element-hq/web-shared-components/numbers";
```

子路径显示以下所列相同的函数: [格式化](https://npmcn.com/package/%40element-hq/web-shared-components/#readme-formatting) 和船舶作为自己的ES/CJS `dist/numbers.{js,umd.cjs}`更倾向于 其它一切的主包条目 .

### 使用组件

这个库有两种组件:

-   _常设经常_ 反应组件不遵循特定模式.
-   _视图_ 组件(MVVM模式).

> \[TIP\] 项目故事书载有这些内容.

#### 常规组件

这些组件可以通过路过道具直接使用. 示例

```tsx
import { Flex } from "@element-hq/web-shared-components";
function MyApp() {
    return <Flex align="center" />;
}
```

#### 查看( MVVM) 组件

这些组成部分遵循 [MVVM 模式](https://npmcn.com/package/docs/MVVM.md)视图模式 实例应作为道具提供.

这里有一个基本的例子:

```tsx
import { ViewExample } from "@element-hq/web-shared-components";

function MyApp() {
    const viewModel = new ViewModelExample();
    return <ViewExample vm={viewModel} />;
}
```

### 公用事业

#### 国际化

-   `useI18n()` - 钩去翻译
-   `I18nApi` - 国际化的API公用事业

#### 日期和时间

-   `DateUtils` - 日期格式化和操纵
-   `humanize` - 人类可读时间格式化

#### 格式化

-   `FormattingUtils` - 文本和数据格式化公用事业
-   `numbers` - 公用事业的格式编号

## 发展

### 先决条件

-   节点.js >= 20.0.0
-   pnpm 第10页

### 设置

```bash
# Install dependencies
pnpm install

# Build the library
pnpm prepack
```

### 运行故事本

```bash
pnpm storybook
```

### 写入组件

大部分组件应为: [MVVM 模式](https://npmcn.com/package/docs/MVVM.md) 视图 组件。 实例见现有组件。 例外程度低 不需要视图模型的组件.

### 写故事书故事

所有组件都应附有故事书故事,供文献和视觉测试使用。 故事使用 TypeScript 写入 [组件故事格式( CSF)](https://storybook.js.org/docs/api/csf)。 。 。 .

使用浅浅、面向浏览的故事标题,例如 `RoomList/RoomListSearchView` 或者说 `TimelineBody/DecryptionFailureBodyView`。不要在故事书标题中镜像全部源路径.

#### 故事文件结构

将故事文件放在组件旁边 `.stories.tsx` 扩展名 :

```
MyComponent/
├── MyComponent.tsx
├── MyComponent.module.css
└── MyComponent.stories.tsx
```

#### 常规部分

对于正则回放组件(non-MVVM),通过定义元对象和故事变化来创建故事:

```tsx
import type { Meta, StoryObj } from "@storybook/react-vite";
import { fn } from "storybook/test";
import { MyComponent } from "./MyComponent";

const meta = {
    title: "Category/MyComponent",
    component: MyComponent,
    tags: ["autodocs"],
    args: {
        // Default args for all stories
        label: "Default Label",
        onClick: fn(), // Mock function for tracking interactions
    },
} satisfies Meta<typeof MyComponent>;

export default meta;
type Story = StoryObj<typeof meta>;

// Default story uses the default args
export const Default: Story = {};

// Override specific args for variations
export const WithCustomLabel: Story = {
    args: {
        label: "Custom Label",
    },
};

export const Disabled: Story = {
    args: {
        disabled: true,
    },
};
```

#### MVVM 组件故事

对于 MVVM 组件, 创建一个使用 `useMockedViewModel` 财务报告和审定财务报表 `withViewDocs`数字 :

```tsx
import React, { type JSX } from "react";
import { fn } from "storybook/test";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { MyComponentView, type MyComponentViewSnapshot, type MyComponentViewActions } from "./MyComponentView";
import { useMockedViewModel } from "../../viewmodel";
import { withViewDocs } from "../../../.storybook/withViewDocs";

// Combine snapshot and actions for easier typing
type MyComponentProps = MyComponentViewSnapshot & MyComponentViewActions;

// Wrapper component that creates a mocked ViewModel.
// Must be a named variable (not inline) for docgen to extract its props.
const MyComponentViewWrapperImpl = ({ onAction, ...rest }: MyComponentProps): JSX.Element => {
    const vm = useMockedViewModel(rest, {
        onAction,
    });
    return <MyComponentView vm={vm} />;
};
// withViewDocs copies the View's JSDoc description onto the wrapper for Storybook autodocs
const MyComponentViewWrapper = withViewDocs(MyComponentViewWrapperImpl, MyComponentView);

// Must use `satisfies` (not `as` or `: Meta`) to preserve type info for docgen
const meta = {
    title: "Category/MyComponentView",
    component: MyComponentViewWrapper,
    tags: ["autodocs"],
    args: {
        // Snapshot properties (state)
        title: "Default Title",
        isLoading: false,
        // Action properties (callbacks)
        onAction: fn(),
    },
} satisfies Meta<typeof MyComponentViewWrapper>;

export default meta;
type Story = StoryObj<typeof MyComponentViewWrapper>;

export const Default: Story = {};

export const Loading: Story = {
    args: {
        isLoading: true,
    },
};
```

由于这种方法,我们可以在故事论证中直接使用原始语来代替取景模型对象.

> \[大 要在Storybook的ArgTypes表格中显示快照字段文档,必须满足三项要求:
> 
> 1.  **已命名的包装变量** - 包装必须指定给一个有名的 `const` (例如:. `MyComponentViewWrapperImpl`) 被传递至 `withViewDocs`,这样 `react-docgen-typescript` 可以提取道具.
> 2.  **`withViewDocs` 调用** ——用原"取景"将包装组件包起来,复制"取景"的"JSDoc"描述.
> 3.  **`satisfies Meta`** ——元对象必须使用 `satisfies Meta<...>` (无) `as Meta<...>` 或者说 `: Meta<...> =`) (中文(简体) ). 类型断言和说明去除Docgen所依赖的所推断的成分类型.

#### 链接图像设计

此软件包使用 [@ storybook/addon-designs (英语)](https://github.com/storybookjs/addon-designs) 将 Figma 设计直接嵌入到故事书中。 这有助于开发者将其执行与设计规格进行比较.

1.  **获取图像 URL**:在Figma中打开您的设计,点击"Share" → "Copy link"
2.  **添加到故事参数**: 包含 `design` 元中的对象 `parameters`
3.  **支持的 URL 格式**数字 :
    -   文件链接 : `https://www.figma.com/file/...`
    -   设计链接 : `https://www.figma.com/design/...`
    -   特定节点 : `https://www.figma.com/design/...?node-id=123-456`

图片集成示例:

```tsx
const meta = {
    title: "RoomList/RoomListSearchView",
    component: RoomListSearchViewWrapper,
    tags: ["autodocs"],
    args: {
        // ... your args
    },
    parameters: {
        design: {
            type: "figma",
            url: "https://www.figma.com/design/vlmt46QDdE4dgXDiyBJXqp/ER-33-Left-Panel?node-id=98-1979",
        },
    },
} satisfies Meta<typeof RoomListSearchViewWrapper>;

export default meta;
```

Figma设计将在"故事本""设计"分页中出现.

#### 非UI 用户故事

对于公用功能,帮助者,以及其他非UI导出,使用TypeDoc生成的平分格式创建文档故事.

`src/core/utils/humanize.stories.tsx`

```tsx
import React from "react";
import { Markdown } from "@storybook/addon-docs/blocks";

import type { Meta } from "@storybook/react-vite";
import humanizeTimeDoc from "../../typedoc/functions/humanizeTime.md?raw";

const meta = {
    title: "Core/Humanize",
    parameters: {
        docs: {
            page: () => (
                <>
                    <h1>humanize</h1>
                    <Markdown>{humanizeTimeDoc}</Markdown>
                </>
            ),
        },
    },
    tags: ["autodocs", "skip-test"],
} satisfies Meta;

export default meta;

// Docs-only story - renders nothing but triggers autodocs
export const Docs = {
    render: () => null,
};
```

> \[注\] 一定要包括 `skip-test` 标记在您的实用故事中,防止它们作为视觉测试运行.

**工作流量 :**

1.  在工具函数中写入 TsDoc
2.  导出函数从 `src/index.ts`
3.  运行 `pnpm build:doc` 生成类型 Doc 标记
4.  创建一个 `.stories.tsx` 文件导入生成的标记下
5.  文档在故事书中自动显示

### 测试

有两种测试:单位测试和视觉回归测试.

### 单位测试

这些测试涵盖了组件和公用事业的逻辑。 由维特建造 和反应测试库.

```bash
pnpm test:unit
```

### 视觉回归测试

这些测试确保了UI组件的正确渲染. 以"故事"为主线,利用剧作家在vitest下跑.

```bash
pnpm test:storybook:update
```

每一个故事都会被呈现出来, 并会拍摄一个截图, 并比照 现有基线。 如果出现视觉变化或AXE违规,测试会 失败.

屏幕截图位于 `packages/shared-components/__vis__/`。 。 。 .

> \[大 如果和Playwright有麻烦,请看 [剧作家 EW 文档](https://github.com/element-hq/element-web/blob/develop/docs/playwright.md#supported-container-runtimes)。 。 。 .

### 翻译

先看看我们的 [翻译指南](https://npmcn.com/package/docs/translating.md) 财务报告和审定财务报表 [翻译 dev 指南](https://npmcn.com/package/docs/translating-dev.md)。 。 。 . 要生成此软件包的翻译字符串, 请运行 :

```bash
pnpm i18n
```

## 发布新版本

为了执行释放,见文件: [`../RELEASING.md`](https://npmcn.com/package/%40element-hq/RELEASING.md)。 。 。 .

## 常见问题

### @element-hq/web-shared-components 是什么？

元素共享组件

### 如何安装 @element-hq/web-shared-components？

在项目目录运行 npm install @element-hq/web-shared-components，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：react（^19\.0\.0）、react-dom（^19\.0\.0）、@vector-im/compound-web（^8\.3\.5 \|\| ^9\.0\.0 \|\| ^10\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @element-hq/web-shared-components 支持 TypeScript 吗？

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

### @element-hq/web-shared-components 支持 ESM 还是 CommonJS？

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

### @element-hq/web-shared-components 需要什么版本的 Node\.js？

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

### @element-hq/web-shared-components 可以商用吗？

@element-hq/web-shared-components 使用 未声明 许可。package\.json 没有声明许可证。没有许可证的代码默认保留全部权利，商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括，不构成法律意见，请以许可原文为准。

### @element-hq/web-shared-components 的下载量有多少？

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

### @element-hq/web-shared-components 还在维护吗？

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

