Live Preview for VS Code

repository·main·Indexed 20 days ago

https://github.com/microsoft/vscode-livepreview

A VS Code extension that hosts a local server to preview web projects (HTML/CSS/JS) directly within the editor or in an external browser. It features an embedded preview browser with page history, a URL bar, and console output. The extension supports live refreshing, multi-root workspaces, and workspace-less previewing. It includes a pre-release edition via the live-server package (v0.4.18) and provides developer APIs such as the Connection and BrowserPreview classes for managing server connections and webview navigation.

Tokens
4.7K
Snippets
15
Records
29
Agent score
70%

What's inside Live Preview

  1. Preview files outside of a workspace

    main

    Live Preview supports workspace-less previewing for quick file inspection:

    • The server will use the file's absolute path as the file path.
    • Files are served on their own server instance.
    • Limitations:
      • Linked files may not resolve correctly if they rely on a specific project root.
      • Tasks are not supported outside of a workspace.
    • Stopping the server: If a server is running in the background without a workspace, use the Live Preview: Stop Server command to kill it.
  2. Use the Embedded Preview browser

    main

    The extension provides an in-editor browser for files hosted by the server. Key features include:

    • Page history tracking: Navigate through visited pages.
    • URL bar: Perform address-based navigation.
    • Expandable menu:
      • Preview the current page in an external browser.
      • Perform a page search (use CTRL+F to open the find box and Enter for next result).
      • Open the editor's webview DevTools.
    • Console Output: To view console messages from the embedded preview, open the Output tab in VS Code and select Embedded Live Preview Console from the dropdown menu.
  3. Manage multiple server roots in multi-root workspaces

    main

    In multi-root workspaces, Live Preview opens an additional server for each root you open a preview on.

    To check which ports are currently open for Live Preview, hover over the status bar indicator (typically located in the bottom-right corner of the VS Code window).

  4. Run a persistent server with logging

    main

    If you need a persistent server that logs traffic, you can:

    1. Run a Live Preview task.
    2. Use the command Live Preview: Start Server Logging from the command palette.

    In the server logs, you can click on the traffic entries to open the file location of the file returned by the server.

  5. Preview HTML files with Live Preview

    main

    You can quickly preview HTML files using two methods:

    1. Editor Button: Click the preview button located in the top right corner of the editor.
    2. Context Menu: Right-click the file in the explorer or editor and select the preview option from the context menu.

    This extension is designed for projects where a server is not already provided (e.g., static HTML/CSS/JS projects). For frameworks like React or Angular that require their own dev servers, use the VS Code integrated browser instead.

  6. How the WebSocket server handles live refresh and injectability

    main

    The WSServer manages real-time communication between the VS Code extension and the previewed content. It serves two primary roles:

    1. Live Refreshing: The server sends messages to connected clients (the browsers/iframes) to trigger a page reload when file changes are detected. This is done via the refreshBrowsers() method, which sends a { "command": "reload" } JSON message to all clients.

    2. Injectability Checks: In embedded previews (Webviews), the client uses the WebSocket to check if a target URL is "injectable." An injectable file is one where the extension can inject a custom script to facilitate features like live refresh, address/history relaying, and console output redirection.

    If a file is non-injectable (e.g., certain non-HTML files), the server responds with a foundNonInjectable command containing the path and port. This allows the extension to fallback to a mode that relays the address to the webview without attempting script injection.

  7. Configure Live Refreshing behavior

    main

    By default, changes in the editor appear in the preview immediately. You can customize this behavior in the extension settings using the livePreview.autoRefreshPreview key.

    Opting out of Live Refreshing: To prevent a specific page from refreshing automatically, add the data-server-no-reload attribute to the <body> tag in your HTML:

    <body data-server-no-reload>
      <!-- Content that won't trigger a reload -->
    </body>
  8. Troubleshoot relative file link errors

    main

    If you see the error: "Previewing a file that is not a child of the server root. To see fully correct relative file links, please open a workspace at the project root or consider changing your server root settings for Live Preview."

    This occurs because the server is hosted from the workspace root (or the directory specified in livePreview.serverRoot). To fix this:

    1. Open a workspace: Ensure you have a workspace open at the actual root of your web project.
    2. Check Server Root: Verify if livePreview.serverRoot is set to a sub-folder that excludes your current file.
    3. Workspace-less mode: If no workspace is open, the server uses absolute paths, which can break relative links.
  9. Fix Embedded Preview in GitHub Codespaces

    main

    If the embedded preview is not working in Codespaces, you must manually handle port forwarding:

    1. Navigate to the Ports tab in the area where the integrated terminal is located.
    2. Find the forwarded ports (usually 3000 and 3001).
    3. Use CTRL+Click on the local addresses to open them in your browser.
    4. Allow the browser to perform necessary redirects, then close the windows.
    5. Re-open the preview window in VS Code.
  10. Configure Live Preview settings

    main

    Live Preview settings are managed under the livePreview configuration section in VS Code. You can configure various behaviors such as the server port, refresh frequency, and preview target.

    Key configuration options include:

    • portNumber: The port used by the local server (default: 3000).
    • autoRefreshPreview: Controls when the preview refreshes. Options are On All Changes in Editor, On Changes to Saved Files, or Never.
    • openPreviewTarget: Determines if the preview opens in an Embedded Preview or an External Browser.
    • customExternalBrowser: If using an external browser, you can specify Edge, Chrome, Firefox, or Default.
    • hostIP: The IP address to bind the server to (default: 127.0.0.1).
    • useIntegratedBrowser: Whether to use the integrated browser (default: true).
    • httpHeaders: Custom HTTP headers to include in the server response.
    {
      "livePreview": {
        "portNumber": 3000,
        "autoRefreshPreview": "On All Changes in Editor",
        "openPreviewTarget": "Embedded Preview",
        "hostIP": "127.0.0.1",
        "useIntegratedBrowser": true
      }
    }