Publish Vega visualizations as embedded web components.
—
Main embedding functionality for integrating Vega and Vega-Lite visualizations into web applications. The embed function handles spec loading from URLs or objects, automatic mode detection, and comprehensive configuration options.
Primary function for embedding Vega/Vega-Lite visualizations into DOM elements.
/**
* Embed a Vega or Vega-Lite visualization into a DOM element
* @param el - DOM element or CSS selector string indicating where to embed
* @param spec - Vega/Vega-Lite specification as object or URL string
* @param opts - Optional configuration options
* @returns Promise resolving to Result object with view instance and metadata
*/
function embed(
el: HTMLElement | string,
spec: VisualizationSpec | string,
opts?: EmbedOptions
): Promise<Result>;Usage Examples:
import embed from "vega-embed";
// Embed with DOM element
const element = document.getElementById("vis");
const result = await embed(element, spec);
// Embed with CSS selector
const result = await embed("#vis", spec);
// Embed with options
const result = await embed("#vis", spec, {
renderer: "svg",
actions: false,
theme: "dark"
});
// Load spec from URL
const result = await embed("#vis", "https://example.com/chart.json");The embed function returns a comprehensive result object containing the view instance and metadata.
interface Result {
/** The instantiated Vega view instance */
view: View;
/** Copy of the input specification */
spec: VisualizationSpec;
/** The compiled and patched Vega specification */
vgSpec: VgSpec;
/** The embed options that were used */
embedOptions: EmbedOptions;
/** Cleanup function to prevent memory leaks */
finalize: () => void;
}Usage Examples:
const result = await embed("#vis", spec);
// Access the Vega view for interactions
result.view.addEventListener('click', (event, item) => {
console.log('Clicked:', item);
});
// Get the final compiled spec
console.log(result.vgSpec);
// Clean up when done
result.finalize();Union type supporting both Vega and Vega-Lite specifications.
type VisualizationSpec = VlSpec | VgSpec;The embed function automatically detects the specification format and handles compilation as needed. Vega-Lite specs are compiled to Vega specs internally.
The embed function is async and may throw errors for various conditions:
try {
const result = await embed("#vis", spec);
} catch (error) {
console.error("Embedding failed:", error);
}Common error scenarios:
Install with Tessl CLI
npx tessl i tessl/npm-vega-embed