vite-plugin-web-extension

repository·main·Indexed 43 days ago

https://github.com/samrum/vite-plugin-web-extension

A Vite plugin for generating cross-browser, ES module-based web extensions. It simplifies Manifest V2 and V3 development, providing support for content scripts as ES modules, HMR within Shadow DOMs via addViteStyleTarget, and automated manifest parsing. Version 5.1.1 supports various frameworks including React, Vue, Svelte, Solid, and Preact.

Tokens
5.1K
Snippets
16
Records
26
Agent score
56%

What's inside vite-plugin-web-extension

  1. Add Devtools Panels to your extension

    main

    To add content to the browser developer tools, add a devtools_page entry to your manifest pointing to an HTML file.

    1. Manifest: Add devtools_page: "src/entries/devtools/index.html".
    2. Setup Script: Place a devtools.js file in your public directory to create the panel.
    3. HTML: Load the devtools.js script within your devtools HTML file.

    Example public/devtools.js:

    var _browser;
    if (chrome) {
      _browser = chrome;
    } else {
      _browser = browser;
    }
    _browser.devtools.panels.create(
      "My Panel", // title
      "images/icon-16.png", // icon
      "src/entries/devtools/index.html" // content
    );

    Example src/entries/devtools/index.html:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <title>Devtools</title>
      </head>
      <body>
        <div id="app"></div>
        <script type="module" src="./main.ts"></script>
        <script src="/devtools.js"></script>
      </body>
    </html>
  2. Migrate from Version 3.x.x to 4.0.0

    main

    When upgrading from version 3.x.x to 4.0.0, apply the following changes:

    • Dev mode HTML transforms: These are no longer applied by default. If your project requires them, you must explicitly enable them using the devHtmlTransform option.
    • Rename option: The useDynamicUrlContentScripts option has been renamed to useDynamicUrlWebAccessibleResources.
    • Replace webAccessibleScripts: The webAccessibleScripts option has been removed. To achieve similar functionality, use the additionalInputs option. Move scripts to additionalInputs.scripts and HTML files to additionalInputs.html.
  3. Configure Experimental Manifest V3 for Firefox

    main

    Firefox's experimental Manifest V3 support has two requirements that must be addressed in your configuration:

    1. Background Scripts: Since background service workers are not supported in Firefox's experimental MV3, you must use a background script instead of a service worker.
    2. Web Accessible Resources: The use_dynamic_url property is not supported. You must set useDynamicUrlWebAccessibleResources to false in the plugin options.
    webExtension({
      ... 
      useDynamicUrlWebAccessibleResources: false,
    }),
  4. Enable HMR for Shadow DOM in Content Scripts

    main

    To support Hot Module Replacement (HMR) for styles inside a Shadow DOM, use the addViteStyleTarget function from the @samrum/vite-plugin-web-extension/client package to register your shadowRoot as a target.

    if (import.meta.hot) {
      const { addViteStyleTarget } = await import(
        "@samrum/vite-plugin-web-extension/client"
      );
    
      await addViteStyleTarget(appContainer);
    }
  5. Quick Start with @samrum/vite-plugin-web-extension

    main

    To create a new Vite-based web extension project with pre-configured support for Manifest versions, TypeScript, and various frameworks (Preact, React, Solid, Svelte, Vanilla, Vue), use the following command:

    npm init @samrum/vite-plugin-web-extension@latest
  6. Migrate from Version 0.x.x to 1.0.0

    main

    When upgrading from version 0.x.x to 1.0.0, apply the following breaking changes:

    • Upgrade Vite: Upgrade Vite to version 2.9.x or higher and upgrade any Vite framework plugins.
    • Update CSS URL imports: Replace import.meta.CURRENT_CONTENT_SCRIPT_CSS_URL with import.meta.PLUGIN_WEB_EXT_CHUNK_CSS_PATHS. Note that import.meta.PLUGIN_WEB_EXT_CHUNK_CSS_PATHS returns an array of strings at build time, so update your code to handle an array instead of a single string.
    • Update Style Target API: Replace the addStyleTarget function from /@vite/client with addViteStyleTarget from @samrum/vite-plugin-web-extension/client.
    • TypeScript Setup: If using TypeScript, add the plugin client types to your env.d.ts file.
    // Replace old style target usage:
    // const { addStyleTarget } = await import("/@vite/client");
    // addStyleTarget(shadowRoot);
    
    // With new usage:
    const { addViteStyleTarget } = await import(
      "@samrum/vite-plugin-web-extension/client"
    );
    
    await addViteStyleTarget(shadowRoot);
    
    // And update env.d.ts:
    /// <reference types="@samrum/vite-plugin-web-extension/client" />
  7. Migrate from Version 4.x.x to 5.0.0

    main
    In version 5.0.0, the devHtmlTransform plugin option has been removed. The plugin now relies on Vite's native dev HTML transform functionality to support HTML files in development (HMR) mode. During development, a <base> element containing the dev server URL for the HTML file is automatically injected into the page to handle resources correctly.
  8. Migrate from Version 2.x.x to 3.0.0

    main

    When upgrading from version 2.x.x to 3.0.0, perform these steps:

    • Upgrade Vite: Ensure Vite is upgraded to version 4.0.3 or higher.
    • Upgrade Framework Plugins: Upgrade any Vite framework plugins to ensure compatibility.
    • Configure build.modulePreload: The plugin now defaults build.modulePreload to false. If your project requires module preloading, you must explicitly define this option in your Vite configuration.
  9. Understand the ManifestParser lifecycle

    main

    The ManifestParser is an abstract class responsible for transforming a web extension manifest by identifying all necessary entry points (scripts, HTML, CSS) and ensuring they are correctly handled by Vite/Rollup.

    It operates in two main phases:

    1. parseInput(): Analyzes the initial manifest to identify all input files (background scripts, content scripts, HTML files, and additionalInputs) that Vite needs to process.
    2. parseOutput(bundle): Analyzes the Rollup output bundle to resolve final filenames, handle CSS/asset dependencies, and optimize web_accessible_resources.

    Key behaviors:

    • Background Scripts: It automatically handles background scripts by wrapping them in an HTML loader to support event pages (specifically for Firefox Manifest V3 support).
    • Content Scripts: It parses content_scripts to ensure both .js and .css files are included in the build process.
    • Web Accessible Resources: If optimizeWebAccessibleResources is enabled in the plugin options, it automatically manages the web_accessible_resources field based on the assets used by chunks.
  10. Configure additionalInputs in ViteWebExtensionOptions

    main

    The additionalInputs option allows you to specify extra files (HTML, scripts, or styles) that are not explicitly mentioned in the manifest but should be included in the extension build.

    When these inputs are processed, the parser ensures they are treated as part of the build and can optionally be made web_accessible.

    Supported types for keys in additionalInputs:

    • html (results in .html extension)
    • scripts (results in .js extension)
    • styles (results in .css extension)

    Note: Filenames containing wildcards (*) are invalid and will throw an error.