Skip to main content
Formats the code in the playground editors using Prettier. By default, code in all editors (markup, style, and script) is formatted. To format only the active editor, pass false as an argument.

Signature

playground.format(allEditors?: boolean): Promise<void>

Parameters

allEditors
boolean
default:"true"
If true (default), formats code in all three editors. If false, formats only the currently active editor.

Returns

Promise<void>
Promise<void>
A promise that resolves when the code formatting is complete.

Usage

Format All Editors

import { createPlayground } from "livecodes";

const playground = await createPlayground("#container", {
  config: {
    markup: {
      language: "html",
      content: "<div><h1>Unformatted</h1></div>",
    },
    style: {
      language: "css",
      content: "body{margin:0;padding:0;}",
    },
    script: {
      language: "javascript",
      content: "const x=1;const y=2;",
    },
  },
});

// Format code in all editors
await playground.format();
// All code is now formatted according to Prettier rules

Format Active Editor Only

import { createPlayground } from "livecodes";

const playground = await createPlayground("#container");

// Format only the currently active editor
await playground.format(false);

Format with Custom Settings

The formatter respects the configuration settings for code style:
import { createPlayground } from "livecodes";

const playground = await createPlayground("#container", {
  config: {
    useTabs: false,
    tabSize: 4,
    semicolons: false,
    singleQuote: true,
    trailingComma: true,
    script: {
      language: "javascript",
      content: "const x = 1; const y = 2;",
    },
  },
});

// Format using the custom settings above
await playground.format();
// Code formatted with 4 spaces, single quotes, no semicolons

Formatter Configuration

The following configuration properties affect code formatting:
  • useTabs - Use tabs instead of spaces (default: false)
  • tabSize - Number of spaces per indentation level (default: 2)
  • semicolons - Use semicolons in JavaScript/TypeScript (default: true)
  • singleQuote - Use single quotes instead of double quotes (default: false)
  • trailingComma - Use trailing commas (default: true)

Notes

  • Not all languages support formatting. The formatter uses Prettier which supports HTML, CSS, JavaScript, TypeScript, JSON, Markdown, and many other languages.
  • Formatting is performed client-side in the browser.
  • If the playground is not yet loaded, calling this method will load it first.
  • getConfig() - Get current configuration including formatter settings
  • setConfig() - Update formatter configuration

Build docs developers (and LLMs) love