@betteroffice/docx-react

中文文档
0.5.1发布于 2026/10/27Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 8.5万

Word-faithful React DOCX editor and viewer: full OOXML fidelity, real-time human + AI agent collaboration.

原始使用文档
文档目录15 节
  1. Install
  2. Usage
  3. Key options
  4. Editor ref
  5. Host saves
  6. Loading and accessibility
  7. Host search
  8. Host proposals
  9. Toolbar and plugins
  10. Edit batches and paragraph anchors
  11. Structured export and content controls
  12. Collaboration
  13. Fonts and localization
  14. Memory and recovery
  15. Documentation

@betteroffice/docx-react

React DOCX editor and viewer with a toolbar, paginated canvas, comments, and tracked changes. The engine runs in a Web Worker by default; document reads, edits, and exports return promises.

Install

bun add @betteroffice/docx-react react react-dom

Peer dependencies: react and react-dom 18 or 19.

Usage

import { DocxEditor } from '@betteroffice/docx-react';
import '@betteroffice/docx-react/styles.css';

export function Editor({ file }: { file: File }) {
  return <DocxEditor documentBuffer={file} />;
}

Import the stylesheet once at the application entry, page, or layout level. Use a browser-only component when integrating with server rendering. See hosting for worker, chunk and CSP needs.

Key options

All props below are optional. Omit the document source to show the placeholder.

proptypedescription
documentBufferArrayBuffer | Uint8Array | Blob | File | nullDOCX source bytes.
fileArrayBuffer | Uint8Array | Blob | File | nullAlias of documentBuffer, which wins when both are set.
fileNamestringAlias of documentName, which wins when both are set.
documentDocument | nullParsed model from @betteroffice/docx, as an alternative source.
mode'editing' | 'suggesting' | 'viewing'Direct edits, tracked changes, or viewing; defaults to 'editing'.
readOnlybooleanDisable editing and hide the default toolbar and rulers.
authorstringAuthor for comments and tracked changes.
onSave(buffer: ArrayBuffer) => voidReceive exported DOCX bytes.
onSaveRequest() => boolean | void | Promise<boolean | void>Own the UI save workflow before serialization.
downloadOnSavebooleanAlso download UI saves; defaults to true.
onDocumentChange(change: DocxDocumentChange) => voidReceive the document version after a committed change.
onError(error: Error, info?: DocxErrorInfo) => voidReceive errors; recoverable reports include recoverable: true.
collaborationDocxEditorCollaborationOptionsConfigure the shared replica.
showToolbarbooleanShow built-in or supplied chrome; defaults to true.
toolbarReactNodeReplace the toolbar; null hides it. Experimental composition API.
showRulerbooleanShow the ruler; defaults to false.
showZoomControlbooleanShow zoom controls; defaults to true.
showHiddenTextbooleanInclude hidden text in layout; defaults to false.
previewFirstPagebooleanExperimental early page preview; off by default and ignored with collaboration.
onFirstPagePainted() => voidCalled once per document when its first pages paint.
pageMirror'full' | 'text'Accessible page DOM; defaults to 'full'.
measurementFontProviderBundledFontProviderOverride the measurement font provider for this editor.
i18nTranslationsLocale overrides from @betteroffice/docx-i18n.
pluginsreadonly DocxPlugin[]Host extensions with managed lifecycle and permissions.
memoryBudgetDocxMemoryBudgetMemory pressure thresholds and an optional worker allocation limit.
onMemoryPressure(pressure: DocxMemoryPressure) => voidReceive memory pressure level changes.

Deprecated: legacySyncApi keeps the synchronous API and is removed in 0.6.0; omit it to use the default async editor.

onChange receives a full Document and works only with legacySyncApi. The default worker editor refuses it, shows an error in place of the document, and reports the error through onError. Use onDocumentChange for version notifications. experimentalWorkerOpen={false} is deprecated; the worker editor is the default.

Editor ref

DocxEditorRef exposes async document operations and the editor's command store, commands. Await save() to export DOCX bytes, or flushPendingInput() before a separate host operation that must include accepted typing and the current selection. Flushing waits for active IME composition and rejects if input fails, the document is replaced, or the editor unmounts. Queued work that cannot run is refused with the exported DocxCommandAdmissionError, whose code names the cause.

Use readPositionAtPoint(clientX, clientY) for a versioned text target at viewport coordinates. Use scrollToParagraph(paraId) for async paragraph navigation. Both support the default worker runtime.

getPositionAtPoint and scrollToParaId throw DocxSyncApiError on the default editor; use readPositionAtPoint and scrollToParagraph.

Host saves

onSaveRequest handles File > Save and Cmd/Ctrl+S before serialization. Return true to continue the built-in save; return false or nothing to suppress it. Async callbacks are awaited, overlapping UI requests share one workflow, and errors reach onError.

Calling save() inside that callback exports directly without invoking onSaveRequest again. onSave receives the exported buffer; downloadOnSave={false} disables the additional UI download.

Loading and accessibility

previewFirstPage paints a display-only preview while the document opens. Editing and plugin activation wait for the full document. onFirstPagePainted lets a host dismiss its loading UI when either preview or full-document pages first appear.

pageMirror="text" keeps readable text, links, and tables with less DOM work. It omits on-page text positions for assistive technology and elements for plugin DOM range queries.

getTotalPages() returns the current, possibly provisional, page count. Await whenLayoutComplete() for the final count; pages outside the viewport are built when shown.

search(query, options?) on the ref highlights body matches, including tables, without moving selection or focus. It returns a promise and works in viewing mode; matching is case-insensitive unless caseSensitive is set. An empty query clears the search.

searchNext() and searchPrevious() wrap through matches; searchGoTo(index) selects a match. Read state with getSearchState(), subscribe with onSearchChange(), and clear with clearSearch().

Host proposals

The ref's proposeChanges(), setProposalStates(), withdrawProposals(), and getProposals() manage tracked changes grouped by host proposal IDs. Decisions preview accepted proposals as plain text and hide rejected ones; withdrawal settles those decisions outside undo history.

Set allowHostProposals to permit proposals in read-only or viewing mode. Set showHostProposalsInSidebar as well to display proposal cards. Both are off by default; proposal access does not enable typing, edit batches, commands, or plugin writes.

Toolbar and plugins

Use the experimental composition API to arrange built-in controls or supply external chrome; see compose the DOCX toolbar. The plugin API is experimental too. For host panels, overlays, sidebar items, lifecycle, and granted operations, see host DOCX editor plugins.

Edit batches and paragraph anchors

The ref's readParagraphs, findText, validateEdits, and applyEdits flush pending input before version-checked operations. See DOCX edit batches and paragraph anchors for target addressing, persisted identities, and refusals.

Structured export and content controls

For exportStructuredWithPages(options) in the default worker editor, see page fragments for revision views, layout requirements, and geometry.

The ref's listContentControls and findContentControls inspect controls before version-checked fills; see content controls.

Collaboration

The collaboration prop connects the worker editor to a shared replica. See the collaboration guide for replica callbacks, shared initial state, transport wiring, and checkpoints.

Fonts and localization

Configure optional measurement fonts before mounting editors; see font setup. Use measurementFontProvider for an editor-specific provider. Embedded font faces are isolated between documents and released when the editor unmounts or loads another document.

Pass locale strings through i18n; strings and translation types are published in @betteroffice/docx-i18n.

Memory and recovery

getMemoryStats() reports main-thread and worker WebAssembly memory. onMemoryPressure reports threshold crossings; memoryBudget defaults to warning at 75% and critical at 90% of 4 GiB. memoryBudget.workerLimitBytes caps worker editing-core allocations.

A failed worker can be replaced once per editor, reopening the source and replaying edits. For byte sources, recovery uses the last checkpoint, so undo history reaches back to that checkpoint. If recovery fails, onError reports the failure and editing stops. Collaboration sessions report worker failure without automatic replacement.

Documentation

版本与发布记录

@betteroffice/docx-react 共发布 14 个版本,首次发布于 2026/07/19;过去 12 个月发布了 14 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.5.1latest2026/10/2712 天前
0.5.02026/10/2613 天前
0.4.32026/10/031 个月前
0.4.22026/10/031 个月前
0.4.12026/10/011 个月前
0.4.02026/10/011 个月前

关于 @betteroffice/docx-react 的常见问题

@betteroffice/docx-react 是什么?

Word-faithful React DOCX editor and viewer: full OOXML fidelity, real-time human + AI agent collaboration.

如何安装 @betteroffice/docx-react?

在项目目录运行 npm install @betteroffice/docx-react,或使用 pnpm add / yarn add / bun add。

@betteroffice/docx-react 支持 TypeScript 吗?

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

@betteroffice/docx-react 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@betteroffice/docx-react 可以商用吗?

@betteroffice/docx-react 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@betteroffice/docx-react 的下载量有多少?

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

@betteroffice/docx-react 还在维护吗?

最新版本 0.5.1 发布于 2026/10/27(12 天前);至今共发布 14 个版本,其中过去 12 个月发布了 14 个;首次发布于 2026/07/19。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。