はじめに
@office-kit/docx はシンプルな関数で構成されたライブラリです。すべての操作は、第 1 引数に Docx 値を受け取る独立したエクスポートとして提供されており、クラスのインスタンスに隠れた状態はありません。そのためパッケージはツリーシェイキングが効き、Node でもブラウザーでも同じように動作します。
インストール
pnpm add @office-kit/docx @office-kit/docx-preview @office-kit/docx がドキュメントを作成・編集するための API です。@office-kit/docx-preview は必要に応じて導入する姉妹パッケージで、任意の Docx 値の読み取り専用プレビューを DOM コンテナにマウントします。どちらも .d.ts 型定義を同梱した ESM として配布されており、Node の組み込みモジュールには依存していません。
ドキュメントをゼロから作成する
createDocx はプレーンな Docx オブジェクトを返し、ほかの API はこれを値として扱います。内容を追加したら toUint8Array を呼び出してファイルのバイト列を取得します。ブラウザーでは toBlob も使えます。
// Build a .docx from scratch. This file is imported as ?raw into the
// docs site so the snippet shown to readers is exactly what svelte-check
// type-checked — if an API rename breaks it, the docs build fails.
import {
addBulletList,
addTable,
appendHeading,
appendParagraph,
createDocx,
PAGE_SIZE_A4,
setPageSize,
toUint8Array,
} from "@office-kit/docx";
const doc = createDocx({ paragraphs: [] });
setPageSize(doc, PAGE_SIZE_A4);
appendHeading(doc, "Quarterly review", 1);
appendParagraph(doc, "Highlights from Q3.");
addBulletList(doc, ["Shipped preview", "Round-trip stable", "Docs site live"]);
addTable(doc, [
["Metric", "Q2", "Q3"],
["MRR", "$120k", "$148k"],
["Churn", "3.1%", "2.4%"],
]);
const bytes: Uint8Array = toUint8Array(doc);
void bytes;
テンプレートを開いてプレースホルダーを埋める
既存の .docx は openDocx で開いて、そのまま編集できます。ライブラリがモデル化していない XML 要素は、すべて元の位置にパススルーノードとして保持されます。そのため、手を加えていないテンプレートを保存しても、別の内容に書き換わることはありません。
replaceTextEverywhere は本文だけでなく、ヘッダー、フッター、脚注、文末脚注、コメントも走査します。Word が 1 つの段落内で複数のランに分割した {{name}} のような文字列も検出できますが、2 つの段落にまたがる文字列は検出されません。
// Open an existing .docx as a template, run cross-part placeholder
// substitution, write it back. The interesting bit: replaceTextEverywhere
// also walks headers, footers, footnotes, endnotes and comments — not just
// the body — so {{name}} in a header swaps out too.
import { readFile, writeFile } from "node:fs/promises";
import { openDocx, replaceTextEverywhere, toUint8Array } from "@office-kit/docx";
const values: Record<string, string> = { name: "Ada Lovelace" };
const doc = openDocx(await readFile("letter-template.docx"));
const replaced = replaceTextEverywhere(
doc,
/\{\{(\w+)\}\}/g,
(m) => values[m.captures[0] ?? ""] ?? "",
);
console.log(`Filled ${replaced} placeholders.`);
await writeFile("letter.docx", toUint8Array(doc));
ブラウザーで表示する
@office-kit/docx-preview は、Docx またはバイト列の読み取り専用プレビューを DOM コンテナにマウントします。オープンソースの docx-preview レンダラーを previewToDOM という 1 つの関数でラップしたものです。
プレイグラウンドで試せるほか、埋め込み方はレシピで紹介しています。
次のステップ
- レシピ:そのまま使える、よくあるシナリオのコード集。
- API リファレンス:すべての公開エクスポートを分野別に掲載。
- プレイグラウンド:.docx をドロップしてプレビューを確認。
- REPL:コードを編集しながら、生成されるドキュメントを確認。
- GitHub:ソースコードと Issue。