@docx-editor.dev/editor-api

中文文档
2.38.0发布于 2026/11/16LicenseRef-EigenPal-Pro-Evaluation-1.0TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 3.7万

Document automation for DOCX: a batching object model that drives a document from a server or from an editor already open in a page

原始使用文档
文档目录11 节
  1. Guides by task
  2. On a server
  3. Create tracked changes on a server
  4. In the browser
  5. Programming model
  6. Office.js compatibility
  7. Packages
  8. Which API for which job
  9. License
  10. Contributing
  11. Commercial support

DOCX Editor by EigenPal

npm version npm downloads EigenPal Pro License Demo Documentation

@docx-editor.dev/editor-api

Edit DOCX files through a supported subset of the Office.js object model. The API includes paragraphs, ranges, comments, and revisions. Use load() to queue reads and sync() to apply each batch atomically.

Run the API on a server over DOCX bytes or in the browser against an open editor. See Office.js compatibility for supported members and differences from Office.js.

npm install @docx-editor.dev/editor-api @docx-editor.dev/core

Server use requires Node.js ^20.16.0 || >=22.3.0.

Guides by task

Start with Runtime and setup and Batching, loading, and errors.

TaskGuide
Read, insert, replace, or remove textText and ranges
Split a paragraph with insertText() and \n, also as a tracked changeSplit a paragraph
Find matches or use bookmarksSearch and navigation
Set fonts, paragraph properties, styles, or linksFormatting and styles
Create and configure listsLists and numbering
Work with table values, rows, columns, and cellsTables and cells
Insert and resize imagesInline pictures
Insert fields, write their cached results, or calculate PAGE and NUMPAGESFields and pagination
Insert an equation from OOXMLInsert an equation
Propose a split, a field, or an equation as a tracked changeTracked changes
Propose a model's paragraph rewrite as the fewest tracked changesPropose an AI rewrite, with prepareRewrite from @docx-editor.dev/editor-api/agent
Set page geometry and edit headers, footers, or notesPage layout and stories
Fill template controls and edit their metadataContent controls
Discuss content and manage threadsComments
Create, inspect, accept, or reject tracked changesTracked changes
Find any public object, method, property, or support typeAPI member directory

On a server

The root entry opens DOCX bytes, edits the document, and returns the saved bytes.

import { readFile, writeFile } from 'node:fs/promises';
import { DocxEditor } from '@docx-editor.dev/editor-api';

const runtime = await DocxEditor.createServer(await readFile('contract.docx'), {
  author: 'Review bot',
});
try {
  const filled = await runtime.run(async (context) => {
    const matches = context.document.body.search('{{cap}}', { matchCase: true });
    matches.load('items');
    await context.sync(); // Read the matching ranges.

    for (const match of matches.items) match.insertText('$500k', 'Replace');
    await context.sync(); // Commit all writes in one atomic batch.
    return matches.items.length;
  });
  console.log(`replaced ${filled}`);
  await writeFile('contract.filled.docx', await runtime.save());
} finally {
  runtime.dispose();
}

createServer parses the document before resolving and does not retain the input buffer. You can then reuse or transfer that buffer. Each save() returns an independent Uint8Array. Load the saved bytes into a live editor to display server edits.

Create tracked changes on a server

Start with the Office.js developer guide for a complete server example and batching conventions.

Set document.changeTrackingMode = 'TrackMineOnly', then use standard Office.js editing methods. Supply the agent's author when opening the server or collaborative runtime:

await runtime.run(async (context) => {
  const matches = context.document.body.search('within 7 days');
  matches.load('items');
  await context.sync();
  if (matches.items.length !== 1) throw new Error('Choose a unique target');

  context.document.changeTrackingMode = 'TrackMineOnly';
  const replacement = matches.items[0]!.insertText('within 30 days', 'Replace');
  await context.sync();
  replacement.load('text');
  await context.sync();
});

Use range.insertText(text, 'Before' | 'After') for insertions, and range.delete() or range.clear() for deletions. insertText() returns the inserted range. Mode assignments and edits commit together at sync(); failed batches preserve the previous mode and document. Load document.changeTrackingMode before reading it. Off is the initial mode.

This is a supported Office.js subset. TrackMineOnly applies to this server host and persists across its run() calls. It does not change peers' tracking settings or save a document-wide tracking policy. TrackAll fails with NotSupported. Browser tracked writes require the Pro review module; the runtime setting does not change the editor UI mode. Tracked text edits support one paragraph, including table-cell text, and adjacent sibling paragraphs outside collaboration. Tracked Paragraph.delete() and Range.delete() over whole paragraphs record deleted text and deleted paragraph marks, also in collaboration. Font, paragraph-format, paragraph-style, and readingOrder changes record property revisions, and paragraph insertion records inserted text and paragraph marks. Tracked edits can go inside or beside another author's pending text insertion or deletion, and each author's change stays a separate decision. The runtime refuses edits that touch your own pending change, another author's paragraph mark, formatting, move, or structural change, and text inside a row with a pending insertion or deletion. Tracked paragraph splits through insertText() with \n, fields through insertField() with results through Field.result, and one equation at a time through insertOoxml() produce native revisions. Other structural changes refuse while tracking. For the complete list, see Revisions. Comments and revision decisions remain available. Set Off explicitly when permanent edits are intended.

See the server-agent review example for Hocuspocus, stale-read handling, and the review lifecycle.

In the browser

Pass an open core, React, or Vue editor to createBrowser(). Edits use the editor's undo history. Save through the owning editor.

import { DocxEditor } from '@docx-editor.dev/editor-api/browser';

const runtime = DocxEditor.createBrowser(editor, { author: 'Demo Reviewer' });
try {
  await runtime.run(async (context) => {
    const heading = context.document.body.paragraphs.getFirstOrNullObject();
    heading.load('text');
    await context.sync();

    if (!heading.isNullObject) heading.font.bold = true;
    await context.sync();
  });
} finally {
  runtime.dispose();
}

Use the /browser entry for an open editor. Use the root entry on servers to exclude browser rendering code from the bundle.

Supply author for comments, replies, and tracked edits. Browser review writes also require the Pro review module and an editable document. Handle errors by code. See Comments and Tracked changes for supported operations.

Programming model

  • Load properties before reading them. Load collection items before item properties.
  • Batch independent writes with sync(). A failed batch applies no writes; earlier successful syncs remain committed.
  • Sync after insertion before using the returned object.
  • Keep proxies inside runtime.run(), or explicitly track and adopt them across runs.
  • Search again after editing a paragraph. Existing ranges retain their original offsets.
  • Check isNullObject after sync when using a null-object accessor.
  • Check nullable font values and review dates before using them.

See Batching, loading, and errors for transaction limits, proxy lifetimes, and error recovery.

Office.js compatibility

The API implements a documented subset of the Office.js object model. It runs without an Office.js host and does not require an Office.js package. See Office.js compatibility for supported operations, runtime differences, and compatibility reports.

Server page-field updates require a measurer configured with font resources. See Fields and pagination for setup and a runnable report agent.

To upgrade from the former reviewer, bridge, MCP, or chat APIs, see Migration.

Packages

PackageDescription
@docx-editor.dev/reactReact adapter. <DocxEditor>, provider primitives, hooks, and compound chrome.
@docx-editor.dev/coreFramework-agnostic engine: OOXML read/write, canonical document tree, layout, paint.
@docx-editor.dev/i18nShared locale strings and types.
@docx-editor.dev/proTracked changes, comments, and custom nodes.
@docx-editor.dev/editor-apiSupported Office.js subset for document editing on a server or in an open editor.

Which API for which job

Use the React or Vue adapter hooks, the review hooks, and DocxEditorReview from @docx-editor.dev/pro/react or @docx-editor.dev/pro/vue to build browser review controls. Use the editing API in @docx-editor.dev/editor-api for document automation. It follows the Office.js object model and runs in browser and server hosts.

TaskBrowser controls (React or Vue)Document automation
Comment on found texteditor.findMatches, editor.selectMatch, then useReview().commentbody.search, then Range.insertComment
Reply to a threaduseReview().reply(item, text)Comment.reply(text)
Record a tracked replacementSuggesting mode, then editor.exec({ type: 'replaceMatch', match, text })document.changeTrackingMode = 'TrackMineOnly', then Range.insertText(text, 'Replace')
Propose an AI rewrite as tracked changesprepareRewrite through DocxEditor.createBrowserprepareRewrite from @docx-editor.dev/editor-api/agent
Accept or reject a changeuseReview().accept(item) or useReview().reject(item)Revision.accept() or Revision.reject()
Open a change without scrollinguseReview().setActive(key, { reveal: false })Not applicable: no viewport
Highlight rangesuseHighlights(name, source, options)Not applicable
Custom review rail cardsDocxEditorReview with preset set to false, useReviewCardHeights, useStackedReviewPositions, and useReviewRailMetricsNot applicable
Comment-on-selection buttonDocxEditorReview.AddComment as a direct child of DocxEditorReview, or useEditorCommand('review.addComment')Not applicable
Page setup and paragraph dialogsDocxEditor.PageSetupDialog or DocxEditor.ParagraphDialogSection.pageSetup, and Paragraph properties such as alignment

This package ships the task recipes in docs/index.md. They are also on the site: Task recipes.

License

This package uses the EigenPal Pro License. See pricing for license and support options.

Contributing

Contributions welcome. See CONTRIBUTING.md for setup, tests, and the one-time CLA signature.

Commercial support

[!TIP] Questions or custom features? Email [email protected].

版本与发布记录

@docx-editor.dev/editor-api 共发布 68 个版本,首次发布于 2026/08/05;过去 12 个月发布了 68 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.38.0latest2026/11/16今天
2.38.0-canary.20261116033356.sha-2662bd1canary2026/11/16今天
2.38.0-canary.20261115032819.sha-05856f62026/11/151 天前
2.38.0-canary.20261114032659.sha-cdc64af2026/11/142 天前
2.38.0-canary.20261113032851.sha-e2cbc552026/11/133 天前
2.37.02026/11/115 天前

关于 @docx-editor.dev/editor-api 的常见问题

@docx-editor.dev/editor-api 是什么?

Document automation for DOCX: a batching object model that drives a document from a server or from an editor already open in a page

如何安装 @docx-editor.dev/editor-api?

在项目目录运行 npm install @docx-editor.dev/editor-api,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@docx-editor.dev/core(~2.38.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@docx-editor.dev/editor-api 支持 TypeScript 吗?

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

@docx-editor.dev/editor-api 支持 ESM 还是 CommonJS?

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

@docx-editor.dev/editor-api 需要什么版本的 Node.js?

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

@docx-editor.dev/editor-api 可以商用吗?

@docx-editor.dev/editor-api 使用 LicenseRef-EigenPal-Pro-Evaluation-1.0 许可。声明的许可为 LicenseRef-EigenPal-Pro-Evaluation-1.0,请阅读许可原文确认使用条件。以上为概括,不构成法律意见,请以许可原文为准。

@docx-editor.dev/editor-api 的下载量有多少?

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

@docx-editor.dev/editor-api 还在维护吗?

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