* feat: live examples in the docs, which run, draw the document next to the code, and can be edited and downloaded The docs' code examples were plain snippets, often fragments that couldn't run. A code block marked ```ts live is now an example readers can see and change: the page runs it with docx, draws the document it makes next to the code with docx-preview, and offers the .docx to download. Clicking the code opens an editor (Monaco) that knows docx's types, the pages are drawn again as the code changes, and View closes the editor. Split, Code and Preview show the code and the pages side by side, or one of them. The demos a page includes are live too. Every example in the docs that builds or patches a document is now live: 443 of them, each a whole file with its imports, so it runs as written. Code about other things, such as installing, bundlers or servers, stays plain. Running them showed docs that were wrong, fixed here: - Landscape: docx swaps a landscape page's width and height itself, so the docs' swapped sizes made a tall page marked as landscape - Comments: `comments.children` takes plain objects, not `new Comment(...)` - Custom properties are text only - APIs that no longer exist: MathText, Row, `.then` on Packer.toStream, patchDocument(buffer, ...), createParagraph().heading1(), a border's `value`, TextRun's `.break()` - The templates and patcher examples read files that aren't in the repository. They now patch the templates in demo/assets, or make their own `npm run build.docs` copies docx's browser builds into docs/live-examples/lib, so the docs use the docx they describe, and the Pages workflow runs it. The folder is gitignored, and cspell and ESLint skip it. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TmyffPd5QMJYjXiMBQ3EnZ * docs: the bullet examples draw a bullet, and the patcher's usage writes the patched document "ὠ" is U+1F60, a Greek omega, since \u takes four hex digits, so the two live bullet examples on the numbering page drew it as each item's bullet. They use "•" now. The patcher's usage example now awaits patchDocument and writes the document it makes, as the example after it does. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TmyffPd5QMJYjXiMBQ3EnZ --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
10 KiB
Contribution Guidelines
File Documentation
Every source file must include structured JSDoc documentation. This ensures discoverability and traceability back to the OOXML specification.
Module-Level JSDoc
Each file should begin with a module-level JSDoc block containing:
- A brief description of the module's purpose.
- A
Reference:link to the relevant documentation (e.g., officeopenxml.com, datypic.com, or the ECMA-376 standard). - The
@moduletag.
/**
* Header module for WordprocessingML documents.
*
* Headers are repeated at the top of each page in a section.
*
* Reference: http://officeopenxml.com/WPheaders.php
*
* @module
*/
XSD Schema References
Include the relevant XSD schema fragment in a ## XSD Schema section within the JSDoc of classes and factory functions. The ooxml-schemas/ directory in this repository contains the official ISO-IEC29500 OOXML XSD schemas and serves as the golden source of truth.
Key schemas:
| Schema | Purpose |
|---|---|
ooxml-schemas/ISO-IEC29500-4_2016/wml.xsd |
WordprocessingML (main document structure) |
ooxml-schemas/ISO-IEC29500-4_2016/dml-main.xsd |
DrawingML (images, shapes) |
ooxml-schemas/ISO-IEC29500-4_2016/shared-math.xsd |
Math equations |
ooxml-schemas/ISO-IEC29500-4_2016/vml-main.xsd |
VML (legacy shapes, textboxes) |
ooxml-schemas/microsoft/ |
Microsoft's extensions (w14:, wps:...) |
ooxml-schemas/README.md lists every schema and where it's from.
Always cross-reference these schemas when implementing or modifying XML generation:
/**
* Represents a table in a WordprocessingML document.
*
* Reference: http://officeopenxml.com/WPtable.php
*
* @publicApi
*
* ## XSD Schema
* ```xml
* <xsd:complexType name="CT_Tbl">
* <xsd:sequence>
* <xsd:group ref="EG_RangeMarkupElements" minOccurs="0" maxOccurs="unbounded"/>
* <xsd:element name="tblPr" type="CT_TblPr"/>
* <xsd:element name="tblGrid" type="CT_TblGrid"/>
* <xsd:group ref="EG_ContentRowContent" minOccurs="0" maxOccurs="unbounded"/>
* </xsd:sequence>
* </xsd:complexType>
* ```
*/
Code Style and Linting
- Follow Prettier formatting standards. Consider using the Prettier VS Code extension.
- Follow all
ESLintrules configured in the project.
API Design Principles
Every feature should be designed from the consumer's perspective. Before submitting a contribution, verify that your API meets the following criteria:
- Ease of use — Can a developer use this feature with minimal friction?
- Documentation — Are the options, behavior, and examples clearly documented in JSDoc?
- Intuitiveness — Does the API behave as a developer would reasonably expect?
- Declarative style — Does it follow the project's declarative construction pattern?
- Developer experience — Is it pleasant to read and write?
Good Commit Names
Please write good commit messages when making a commit: https://chris.beams.io/posts/git-commit/
Do not:
c // What?
rtl // Adding acronyms without explaining anything else is not helpful
works! // Glad its working, but the message is not helpful
demo updated // Getting better, but capitalize the first letter
Unesesary coment removed // Make sure to use correct spelling
Do
ITableFloatOptions is an interface for a JSON of primitives. The end user would need to pass in a json object and not need to worry about the internals:
public float(tableFloatOptions: ITableFloatOptions): Table
Declarative API
All APIs must be declarative — no method chaining, mutation, or imperative construction patterns. This is a core design principle of the project. See: https://dzone.com/articles/why-declarative-coding-makes-you-a-better-programm
Do not:
const paragraph = doc.createParagraph();
const text = paragraph.createText();
text.contents = "Hello World";
Do:
const doc = new Document({
sections: [
{
children: [
new Paragraph({
children: [new TextRun("Hello World")],
}),
],
},
],
});
Public API Elements (@publicApi)
User-facing elements (e.g., Document, Paragraph, Table, TextRun, Textbox) use the new ClassName(options) pattern and must be annotated with @publicApi in their JSDoc. These form the idiomatic surface of the library that end-users interact with:
/**
* @publicApi
*/
export class Textbox extends FileChild {
public constructor({ style, children, ...rest }: ITextboxOptions) {
// ...
}
}
Internal Elements (BuilderElement)
For internal XML construction — elements that are not part of the public API — use BuilderElement or createXyz() factory functions. This is less verbose while keeping the declarative style intact:
export const createVerticalAlign = (value: VerticalAlignValue): XmlComponent =>
new BuilderElement<{ readonly verticalAlign: VerticalAlignValue }>({
name: "w:vAlign",
attributes: {
verticalAlign: { key: "w:val", value },
},
});
BuilderElement provides typed attributes and optional children in a single declarative call, removing the need for boilerplate wrapper classes for simple XML elements.
Getters and Setters
Getters and Setters are done with a capital letter like so:
public get Level() {
...
}
This is the convention of this project. There is no performance advantage by doing this. It means we don't need to prefix all private variables with _:
Do not:
private get _level: string;
Do
private get level: string;
Types over interfaces
Using type aliases in TypeScript offers several advantages over interfaces:
-
Flexibility with Complex Types:
typesupports defining unions, intersections, and other complex type constructs thatinterfacescannot handle. For example:type StringOrNumber = string | number; type Combined = TypeA & TypeB; -
Support for Primitive Types:
typecan alias primitive types (e.g.,type ID = string), whileinterfacesare limited to object shapes. -
Tuple and Array Types:
typeallows defining tuples and specific array types easily (e.g.,type Point = [number, number]), whichinterfacescannot represent. -
Utility Types Compatibility:
typeworks seamlessly with TypeScript's utility types (e.g.,Partial<T>,Pick<T, K>), enabling more expressive type transformations. -
Functional Programming:
typeis ideal for functional programming patterns, such as defining function signatures or mapped types, due to its versatility. -
No Declaration Merging: Unlike
interfaces, type does not support declaration merging, which can prevent accidental type extensions and ensure predictable type definitions. -
Consistent Pattern: This project uses
typefor all type definitions, so usingtypefor all type definitions maintains consistency and readability across the codebase.
Detailed discussion: https://stackoverflow.com/questions/37233735/typescript-interfaces-vs-types
Do not:
interface IRelationshipFileInfo {
id: number;
target: string;
}
Do:
type RelationshipFileInfo = { id: number; target: string };
String enums vs type
To take full advantage of TypeScript's typing system, its best to use string enums:
Do not:
type WeaponType = "bow" | "sword" | "wand";
Do:
enum WeaponType = {
BOW = "bow",
SWORD = "sword",
WAND = "wand",
}
Spell correctly, in full and in American English
Do not:
readdy; // misspelling
perm; // abbreviation
conf; // abbreviation
cnty; // abbreviation
relationFile; // abbreviation
colour; // U.K. English
Do:
ready;
permission;
config;
country;
relationshipFile;
color;
Keep files small (within reason)
To minimize merge conflicts, reduce complexity, and improve readability, keep the files small.
Name files and folders with /foo-bar/kebab-case.ts
To be consistent and in-line with the project, name files like-this.ts.
https://stackoverflow.com/questions/7273316/what-is-the-javascript-filename-naming-convention
Testing
Please write a test of every file you make and suffix it with .spec.ts.
Here is a template of a test:
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
describe("ClassName", () => {
afterEach(() => {
// TODO
});
beforeEach(() => {
// TODO
});
describe("#methodName()", () => {
it("should ", () => {
// TODO
});
});
});
Live examples in the docs
The code examples in the docs are live: the page runs each one, draws the document it makes next to the code, and lets readers edit the code and download the .docx. Write an example that makes a document as a whole file with its imports, and mark the code block ts live:
```ts live
import { Document, Paragraph } from "docx";
const doc = new Document({
sections: [{ children: [new Paragraph("Hello World")] }],
});
```
The last Document the example makes is the one shown, so it doesn't need Packer. It can still end with Packer.toBuffer and fs.writeFileSync as in Node, and read files in the demo folder with fs.readFileSync, such as ./demo/assets/images/pizza.gif. The demos a page includes from the demo folder are live without being marked. Code that isn't about the document, such as a server handler or bundler setup, stays a plain ts block.
The preview is drawn by docx-preview, which leaves out shapes, charts and watermarks, so check those in Word.
To see the live examples locally, build docx for the docs, then serve them:
npm run build.docs
npm run serve.docs