Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 119 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,125 @@ This will generate two DOCX files in the `example/typescript` directory:
- `basic-example.docx` - A simple document with minimal configuration
- `advanced-example.docx` - A document with headers, footers, and advanced formatting options

## Browser Standalone Build

The library provides a standalone browser build that bundles all dependencies into a single file. This allows you to use the library directly in HTML pages without any build tools or module bundlers.

### Build Outputs

When you run `npm run build`, three distribution files are generated:

| File | Format | Size | Dependencies | Use Case |
|------|--------|------|--------------|----------|
| `dist/html-to-docx.esm.js` | ES Module | ~1.6 MB | External | Modern bundlers (Webpack, Vite, Rollup) |
| `dist/html-to-docx.umd.js` | UMD | ~1.6 MB | External | Node.js, AMD, or manual dependency management |
| `dist/html-to-docx.browser.js` | IIFE | ~2.4 MB | **All bundled** | Direct browser usage, CDN, quick prototypes |

### Build Commands

```bash
# Build all versions (ESM + UMD + Browser)
npm run build

# Build only the browser standalone version (development)
npm run build:browser

# Build only the browser standalone version (production, minified)
npm run build:browser:prod
```

### Browser Usage

Include the standalone browser build directly in your HTML:

```html
<!DOCTYPE html>
<html>
<head>
<title>HTML to DOCX Demo</title>
</head>
<body>
<!-- Polyfills for Node.js globals (required) -->
<script>
if (typeof global === 'undefined') window.global = window;
if (typeof process === 'undefined') window.process = { env: {} };
</script>

<!-- Include the standalone browser build -->
<script src="path/to/html-to-docx.browser.js"></script>

<script>
async function generateDocument() {
const htmlContent = `
<h1>Hello World</h1>
<p>This is a <strong>test document</strong> generated in the browser.</p>
`;

try {
const result = await HTMLToDOCX(htmlContent, null, {
title: 'My Document',
creator: 'Browser App'
});

// Convert result to Blob for download
let blob;
if (result instanceof Blob) {
blob = result;
} else if (result instanceof ArrayBuffer || result instanceof Uint8Array) {
blob = new Blob([result], {
type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
});
}

// Trigger download
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'document.docx';
a.click();
URL.revokeObjectURL(url);
} catch (error) {
console.error('Error generating DOCX:', error);
}
}
</script>

<button onclick="generateDocument()">Generate DOCX</button>
</body>
</html>
```

### Testing the Browser Build

A test page is included to verify the browser build works correctly:

```bash
# Build and start the test server
npm run test:browser
```

Then open http://localhost:8080/tests/test_browser.html in your browser.

The test page allows you to:
- Edit HTML content in a textarea
- Click "Generate DOCX" to create and download a Word document
- See status messages for success or errors

### CDN Usage

You can also host the browser build on a CDN for easy inclusion:

```html
<!-- Example: Self-hosted or CDN -->
<script src="https://your-cdn.com/html-to-docx/1.18.1/html-to-docx.browser.js"></script>
```

### Limitations in Browser Environment

- **Sharp (SVG conversion)**: The `sharp` image processing library is not available in browsers. SVG images will be embedded natively (requires Office 2019+).
- **File System**: No direct file system access. Documents are returned as Blob/ArrayBuffer for download.
- **Image URLs**: Remote images must be CORS-enabled or converted to base64 data URLs.

## Usage

```js
Expand Down
87 changes: 87 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
],
"main": "dist/html-to-docx.umd.js",
"module": "dist/html-to-docx.esm.js",
"browser": "dist/html-to-docx.browser.js",
"types": "index.d.ts",
"files": [
"dist",
Expand All @@ -65,6 +66,7 @@
"test:unit": "jest",
"test:unit:watch": "jest --watch",
"test:unit:coverage": "jest --coverage",
"test:browser": "npm run build && npx -y serve . -l 8080 --no-clipboard",
"prerelease": "npm run build:prod",
"release": "standard-version",
"lint": "eslint --fix .",
Expand All @@ -73,6 +75,8 @@
"build": "rollup -c",
"build:dev": "NODE_ENV=development rollup -c",
"build:prod": "NODE_ENV=production rollup -c",
"build:browser": "cross-env BUILD_TARGET=browser rollup -c",
"build:browser:prod": "cross-env NODE_ENV=production BUILD_TARGET=browser rollup -c",
"diff:docx": "node scripts/diff-docx.js",
"prepare": "husky install",
"postinstall": "node scripts/postinstall.js",
Expand Down Expand Up @@ -140,6 +144,7 @@
"rollup": "^2.62.0",
"rollup-plugin-cleaner": "^1.0.0",
"rollup-plugin-node-builtins": "^2.1.2",
"rollup-plugin-polyfill-node": "^0.13.0",
"rollup-plugin-terser": "^7.0.2",
"standard-version": "^9.3.1",
"ts-node": "^10.9.2",
Expand Down
48 changes: 41 additions & 7 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,17 @@ import commonjs from '@rollup/plugin-commonjs';
import { terser } from 'rollup-plugin-terser';
import cleaner from 'rollup-plugin-cleaner';
import builtins from 'rollup-plugin-node-builtins';
import nodePolyfills from 'rollup-plugin-polyfill-node';

import * as meta from './package.json';

const isProduction = process.env.NODE_ENV === 'production';
const browserOnly = process.env.BUILD_TARGET === 'browser';

export default {
const banner = `// ${meta.homepage} v${meta.version} Copyright ${new Date().getFullYear()} ${meta.author}`;

// Node.js / Library build configuration (ESM and UMD)
const libraryConfig = {
input: 'index.js',
external: ['color-name', 'jszip', 'xmlbuilder2', 'html-entities', 'lru-cache', 'htmlparser2', 'sharp'],
plugins: [
Expand All @@ -29,9 +34,7 @@ export default {
file: 'dist/html-to-docx.esm.js',
format: 'es',
sourcemap: !isProduction,
banner: `// ${meta.homepage} v${meta.version} Copyright ${new Date().getFullYear()} ${
meta.author
}`,
banner,
},
{
file: 'dist/html-to-docx.umd.js',
Expand All @@ -44,9 +47,40 @@ export default {
xmlbuilder2: 'xmlbuilder2',
'html-entities': 'htmlEntities',
},
banner: `// ${meta.homepage} v${meta.version} Copyright ${new Date().getFullYear()} ${
meta.author
}`,
banner,
},
],
};

// Standalone browser build configuration (all dependencies bundled)
const browserConfig = {
input: 'index.js',
// Only exclude sharp (Node.js native module, not supported in browser)
external: ['sharp'],
plugins: [
resolve({
browser: true,
preferBuiltins: false,
}),
json(),
commonjs(),
nodePolyfills(),
terser({
mangle: isProduction,
compress: isProduction,
}),
],
output: {
file: 'dist/html-to-docx.browser.js',
format: 'iife',
name: 'HTMLToDOCX',
sourcemap: !isProduction,
banner,
// Provide empty implementation for sharp in browser environment
globals: {
sharp: '(() => null)',
},
},
};

export default browserOnly ? [browserConfig] : [libraryConfig, browserConfig];
Loading