or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-rollup--plugin-html

Creates HTML files to serve Rollup bundles with extensive customization options for build workflows

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@rollup/plugin-html@2.0.x

To install, run

npx @tessl/cli install tessl/npm-rollup--plugin-html@2.0.0

index.mddocs/

@rollup/plugin-html

@rollup/plugin-html is a Rollup plugin that automatically creates HTML files to serve Rollup bundles. It provides extensive customization options including configurable HTML templates, meta tag injection, script and link attribute customization, and support for multiple output formats (ESM, IIFE, UMD). The plugin handles automatic script and stylesheet inclusion based on bundle outputs, supports custom public paths for asset deployment, and provides utility functions for HTML attribute generation.

Package Information

  • Package Name: @rollup/plugin-html
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @rollup/plugin-html --save-dev
  • Requirements: Node.js v14.0.0+, Rollup v1.20.0+

Core Imports

import html from "@rollup/plugin-html";
import { makeHtmlAttributes } from "@rollup/plugin-html";

For CommonJS:

const html = require("@rollup/plugin-html");
const { makeHtmlAttributes } = require("@rollup/plugin-html");

Basic Usage

import html from "@rollup/plugin-html";

// Basic plugin usage with default settings
export default {
  input: "src/index.js",
  output: {
    dir: "dist",
    format: "es"
  },
  plugins: [html()]
};

// Custom configuration
export default {
  input: "src/index.js", 
  output: {
    dir: "dist",
    format: "iife"
  },
  plugins: [
    html({
      title: "My Application",
      fileName: "app.html",
      publicPath: "/assets/",
      meta: [
        { charset: "utf-8" },
        { name: "viewport", content: "width=device-width, initial-scale=1" }
      ]
    })
  ]
};

Architecture

@rollup/plugin-html integrates into Rollup's build pipeline through the generateBundle hook:

  • Plugin Integration: Registers as a Rollup plugin and processes bundles during the generate phase
  • Bundle Analysis: Automatically detects CSS and JavaScript files from the bundle output
  • Template System: Uses a default HTML template or accepts custom template functions for complete control
  • Format Detection: Automatically handles ES module type attributes and warns about unsupported formats
  • Asset Management: Organizes bundle files by extension and applies appropriate HTML elements

Capabilities

HTML Plugin Function

Creates a Rollup plugin that generates HTML files to serve bundles.

/**
 * A Rollup plugin which creates HTML files to serve Rollup bundles.
 * @param options - Plugin configuration options
 * @returns Plugin instance for Rollup
 */
function html(options?: RollupHtmlOptions): Plugin;

interface RollupHtmlOptions {
  /** Place scripts in the <head> tag instead of <body> */
  addScriptsToHead?: boolean;
  /** HTML attributes for html, link, and script elements */
  attributes?: Record<string, any>;
  /** Name of the HTML file to generate */
  fileName?: string;
  /** Meta tag attributes */
  meta?: Record<string, any>[];
  /** Path to prepend to bundle assets */
  publicPath?: string;
  /** Custom template function for HTML generation */
  template?: (templateOptions: RollupHtmlTemplateOptions) => string | Promise<string>;
  /** HTML document title */
  title?: string;
}

Usage Examples:

// Minimal usage with defaults
html()

// Comprehensive configuration
html({
  title: "My Web App",
  fileName: "index.html", 
  publicPath: "https://cdn.example.com/",
  addScriptsToHead: false,
  attributes: {
    html: { lang: "en", "data-theme": "dark" },
    script: { defer: true },
    link: { crossorigin: "anonymous" }
  },
  meta: [
    { charset: "utf-8" },
    { name: "description", content: "My awesome web application" },
    { name: "viewport", content: "width=device-width, initial-scale=1" }
  ]
})

// Custom template function
html({
  template: ({ attributes, files, meta, publicPath, title }) => {
    const scripts = (files.js || [])
      .filter(file => file.type === 'chunk' && file.isEntry)
      .map(file => `<script src="${publicPath}${file.fileName}"></script>`)
      .join('\n');
    
    const styles = (files.css || [])
      .map(file => `<link href="${publicPath}${file.fileName}" rel="stylesheet">`)
      .join('\n');
    
    return `<!DOCTYPE html>
<html>
  <head>
    <title>${title}</title>
    ${styles}
  </head>
  <body>
    <div id="app"></div>
    ${scripts}
  </body>
</html>`;
  }
})

HTML Attributes Utility

Converts an object of attributes to a space-separated HTML attribute string.

/**
 * Consumes an object with key-value pairs that represent HTML element attribute names and values.
 * Returns all pairs as a space-separated string of valid HTML element attributes.
 * @param attributes - Object with attribute name-value pairs
 * @returns Space-separated string of HTML attributes
 */
function makeHtmlAttributes(attributes: Record<string, any>): string;

Usage Examples:

import { makeHtmlAttributes } from "@rollup/plugin-html";

// Basic attributes
makeHtmlAttributes({ lang: "en", class: "app" });
// Returns: ' lang="en" class="app"'

// Data attributes
makeHtmlAttributes({ 
  "data-theme": "dark", 
  "data-version": "1.0.0",
  id: "main"
});
// Returns: ' data-theme="dark" data-version="1.0.0" id="main"'

// Boolean attributes
makeHtmlAttributes({ defer: true, async: false });
// Returns: ' defer="true" async="false"'

// Empty or null attributes object
makeHtmlAttributes({});
// Returns: ''

makeHtmlAttributes(null);
// Returns: ''

Template Options Interface

Parameters passed to custom template functions.

interface RollupHtmlTemplateOptions {
  /** Scripts placement configuration */
  addScriptsToHead?: boolean;
  /** Element attributes configuration */
  attributes: Record<string, any>;
  /** Complete Rollup output bundle */
  bundle: OutputBundle;
  /** Bundle files organized by extension (js, css, etc.) */
  files: Record<string, (OutputChunk | OutputAsset)[]>;
  /** Meta tag configuration array */
  meta: Record<string, any>[];
  /** Asset path prefix */
  publicPath: string;
  /** HTML document title */
  title: string;
}

Configuration Details

Supported Output Formats

  • Fully Supported: es/esm, iife, umd - These formats work out of the box with the default template
  • Partially Supported: amd, system, cjs - These formats require custom templates and may need additional loaders
  • ES Module Handling: When using es or esm format, type="module" is automatically added to script attributes

Default Configuration

const defaults = {
  attributes: {
    link: null,
    html: { lang: "en" },
    script: null
  },
  fileName: "index.html",
  meta: [{ charset: "utf-8" }],
  publicPath: "",
  template: defaultTemplate, // Internal default template
  title: "Rollup Bundle",
  addScriptsToHead: false
};

File Organization

The plugin automatically organizes bundle files by extension:

  • JavaScript files (files.js): Script tags are created for entry chunks only
  • CSS files (files.css): Link tags are created for all CSS assets
  • Other assets: Available in the files object but not automatically included in default template

Error Handling

  • Unsupported Formats: Plugin warns when using unsupported output formats without a custom template
  • Missing Assets: Gracefully handles bundles without CSS or JavaScript files
  • Template Errors: Template function errors are propagated to Rollup's error handling

Types

// From Rollup core - used in plugin interfaces
interface Plugin {
  name: string;
  generateBundle?(
    options: NormalizedOutputOptions, 
    bundle: OutputBundle
  ): void | Promise<void>;
}

interface OutputBundle {
  [fileName: string]: OutputAsset | OutputChunk;
}

interface OutputChunk {
  type: 'chunk';
  fileName: string;
  isEntry: boolean;
  // ... other Rollup chunk properties
}

interface OutputAsset {
  type: 'asset';
  fileName: string;
  source: string | Uint8Array;
  // ... other Rollup asset properties
}

interface NormalizedOutputOptions {
  format: string;
  // ... other Rollup output options
}