@betteroffice/docx

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

Word-faithful DOCX editor and viewer core: full OOXML fidelity, real-time human + AI agent collaboration. Framework-free (Rust/Wasm).

原始使用文档
文档目录17 节
  1. Install
  2. Usage
  3. Entry points
  4. Runtime and assets
  5. Undo grouping
  6. Selection state
  7. Host proposals
  8. Comment ranges
  9. Edit batches
  10. Paragraph anchors
  11. Structured export
  12. Content controls
  13. Compare documents
  14. Collaboration
  15. Editor plugins
  16. Fonts for custom adapters
  17. Documentation

@betteroffice/docx

Framework-free DOCX parsing, serialization, CRDT editing, layout, and canvas rendering backed by Rust/WebAssembly. Use it for document processing or a custom editor adapter.

Install

bun add @betteroffice/docx

@betteroffice/fonts is an optional peer dependency for font assets.

Usage

Parse a DOCX and save it while preserving untouched package parts:

import { readFile, writeFile } from 'node:fs/promises';
import { parseDocx, repackDocx } from '@betteroffice/docx';

const document = await parseDocx(await readFile('input.docx'));
// document.package.document.content: the body's paragraphs and tables
// document.package also holds styles, numbering, theme, media, headers and footers
const bytes = await repackDocx(document);
await writeFile('output.docx', new Uint8Array(bytes));

Entry points

entry pointdescription
parseDocxRead an ArrayBuffer, Uint8Array, Blob, or File into a document model.
repackDocx, repackDocxWithWarningsSave a parsed model against its original package; the latter also returns save warnings.
createDocxWrite a new document model without an original package.
createYrsSession (from @betteroffice/docx/yrs)Asynchronously create a CRDT editing session.
saveYrsDocx (from @betteroffice/docx/yrs)Save a session opened from DOCX bytes, returning bytes and persisted paragraph anchors.

For a React editor and viewer, use @betteroffice/docx-react.

Runtime and assets

The package ships container, parser, layout, and editing WebAssembly assets in dist/generated/. Async entry points load the assets they need; no manual initialization is required for parsing or creating a session. Preserve the packaged asset URLs when bundling for a browser.

Core sessions expose synchronous editing and read methods after asynchronous creation. The React editor runs its engine in a Web Worker by default and exposes promise-returning document reads, edits, and exports. Release a direct session with session.destroy() when finished.

Undo grouping

A story is one text flow: the body, a header or footer, a footnote, or a comment. session.setUndoCaptureMode(mode) selects how local transactions group into undo steps; session.undoCaptureMode() reads the mode. Call session.beginUndoCapture() after import or seeding.

ModeGrouping
auto (default)Nearby edits coalesce; switching stories closes the group.
manualEdits coalesce until an explicit boundary, including across stories.

session.addUndoBoundary() closes the current group. Changing modes also closes it while keeping history; setting the same mode does not. In manual mode, close groups before unrelated edits. Remote transactions stay outside local undo history; edit batches supply atomic execution.

Selection state

session.selectionContext(range) aggregates formatting across a paragraph-addressed selection. Toggle formatting is true, false, or 'mixed'; value formatting is null when absent or nonuniform. Use this state to drive custom formatting controls.

Host proposals

session.proposeChanges({ expectVersion, proposals }) applies a version-checked round of tracked changes grouped by host proposal IDs, outside undo history. Each proposal names its id, target paragraph, an op (replaceText or insertText) and suggest: { author, date } for attribution. A refusal leaves the round unapplied.

session.setProposalStates({ expectVersion, expectPreviewVersion, changes }) changes how proposals preview without changing the document or undo history. session.withdrawProposals({ expectVersion, ids }) settles accepted proposals as plain text and removes rejected or undecided ones, so later rounds search the text shown by the preview.

Read the registry with session.getProposals() or observe it with session.onProposalChange(). Opening another document clears the registry. Use proposalRevisionPreview(snapshot) from @betteroffice/docx/yrs as the layout render environment's revisionPreview to display decisions.

Comment ranges

session.setCommentRanges(commentId, ranges) replaces an existing comment's sticky anchors while preserving its metadata. Ranges may span paragraphs or address separate stories; each must be nonempty, ordered, and within existing paragraphs. Invalid input throws before changing the comment.

Reanchoring joins local undo capture. saveYrsDocx(session) writes the current ranges; a host that removes all commented text must choose a surviving range or remove the comment.

Edit batches

Read targets with their session version, then apply all steps atomically against that version. See version-checked DOCX batches for operations, offsets, limits, and typed refusals.

Paragraph anchors

Session paragraph keys identify paragraphs within a collaborative session; persisted anchors identify saved paragraphs by package part and OOXML paragraph ID. See DOCX paragraph anchors for saving, reopening, resolving, and assigning IDs.

Structured export

For exportDocxStructured and exportDocxMarkdown, see structured content for anchored JSON or Markdown, revision views, story selection, and live-session exports.

For exportDocxStructuredWithPages, see page fragments for font requirements, layout maps, and page geometry.

Deprecated: collectHeadings from @betteroffice/docx/utils; use session.headings(story) instead.

Content controls

listDocxContentControls and findDocxContentControls inspect controls in DOCX bytes. See content controls for session discovery, version-checked fills, and supported control types.

Compare documents

compareDocx compares two DOCX files and returns tracked text changes or diagnostics. See DOCX comparison for supported inputs, attribution, and refusal behavior.

Collaboration

CollaborationProvider from @betteroffice/docx/collaboration connects a replica to a binary transport. See the collaboration guide for shared state, transport wiring, checkpoints, and deployment.

Editor plugins

For React host extensions, use the DOCX plugin API.

Deprecated: EditorPluginCore, PluginPanelProps, PanelConfig, and SidebarItemContext from @betteroffice/docx/plugin-api; use defineDocxPlugin and plugins from @betteroffice/docx-react.

Fonts for custom adapters

See font setup for optional measurement assets. For browser font loading, createFontLoadScope() from @betteroffice/docx/utils isolates each editor's load notifications. registerDocumentFaces(faces, scope) registers embedded faces and returns their CSS family aliases when documents use different bytes under the same family name. Release the scope with scope.dispose() when its editor is removed.

Documentation

版本与发布记录

@betteroffice/docx 共发布 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 的常见问题

@betteroffice/docx 是什么?

Word-faithful DOCX editor and viewer core: full OOXML fidelity, real-time human + AI agent collaboration. Framework-free (Rust/Wasm).

如何安装 @betteroffice/docx?

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

@betteroffice/docx 支持 TypeScript 吗?

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

@betteroffice/docx 支持 ESM 还是 CommonJS?

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

@betteroffice/docx 可以商用吗?

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

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

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

@betteroffice/docx 还在维护吗?

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