Skip to content

Conversation

@ricardo-devis-agullo
Copy link
Collaborator

Add preload script support for component preview

Overview

This PR introduces a new preload configuration option that allows developers to inject custom JavaScript code into the component preview HTML's <head> section during development. This enables advanced debugging, analytics, polyfills, or any other client-side functionality that needs to execute before component rendering.

Changes

Configuration Interface

  • Added preload?: string to the development section of OpenComponentsConfig
  • Updated ParsedConfig type to include the preload option
  • Enhanced TypeScript definitions with comprehensive JSDoc documentation

File Processing Logic

  • Implemented smart file detection in options-sanitiser.ts that distinguishes between file paths and inline JavaScript
  • Added automatic file reading for .js files with proper error handling and fallback behavior
  • Supports both absolute and relative file paths with automatic resolution

Preview Integration

  • Modified the preview template to inject preload scripts directly into the HTML <head>
  • Updated the component preview route to pass preload configuration through the rendering pipeline
  • Enhanced the dev facade to read and forward preload configuration from local config

Usage

The preload option accepts either a file path or inline JavaScript:

{
  "development": {
    "preload": "./scripts/debug.js"
  }
}
{
  "development": {
    "preload": "console.log('Component preview loaded'); window.myGlobalVar = true;"
  }
}

Technical Details

The implementation uses a heuristic approach to determine whether the preload value is a file path or inline code:

  • If the string doesn't contain ; or { characters, it's treated as a file path
  • File paths are resolved relative to the current working directory
  • If file reading fails, the original value is preserved (allowing inline JS to work as fallback)
  • All file operations include proper error handling with warning messages

This approach provides maximum flexibility while maintaining backward compatibility and graceful error handling.

@ricardo-devis-agullo ricardo-devis-agullo merged commit 8bb3517 into master Sep 1, 2025
3 checks passed
@ricardo-devis-agullo ricardo-devis-agullo deleted the preload-option branch September 1, 2025 07:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants