Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@ugurkellecioglu/vite-plugin-web-extension

ugurkellecioglu25MIT5.1.3TypeScript support: included

A vite plugin for generating cross browser platform, ES module based web extensions

vite, vite-plugin, web, extension, browser, chrome, firefox, edge, manifest, manifest V2, manifest V3

readme

@samrum/vite-plugin-web-extension

npm version node compatibility ci

Generate cross browser platform, ES module based web extensions.

  • Manifest V2 & V3 Support
  • Completely ES module based extensions
    • Including in content scripts!
  • Vite based html and static asset handling
    • Including in content scripts!
  • HMR support
    • All Manifest entry points
      • Including content scripts when using a Chromium browser!
    • CSS styles in content scripts
      • Including shadow DOM rendered content!
    • Including Manifest V3 support since Chromium 110!

Quick Start

Create a new Vite web extension project

npm init @samrum/vite-plugin-web-extension@latest

Supports choice of Manifest version, TypeScript support, and framework (Preact, React, Solid, Svelte, Vanilla, Vue).

Check the README of the generated extension for usage information.

Usage

Requires Vite 3+

npm install @samrum/vite-plugin-web-extension

Examples

<summary>Manifest V2</summary>

vite.config.js:

import { defineConfig } from "vite";
import webExtension from "@samrum/vite-plugin-web-extension";

export default defineConfig({
  plugins: [
    webExtension({
      manifest: {
        name: pkg.name,
        description: pkg.description,
        version: pkg.version,
        manifest_version: 2,
        background: {
          scripts: ["src/background/script.js"],
        },
      },
    }),
  ],
});
<summary>Manifest V3</summary>

vite.config.js:

import { defineConfig } from "vite";
import webExtension from "@samrum/vite-plugin-web-extension";

export default defineConfig({
  plugins: [
    webExtension({
      manifest: {
        name: pkg.name,
        description: pkg.description,
        version: pkg.version,
        manifest_version: 3,
        background: {
          service_worker: "src/background/serviceWorker.js",
        },
      },
    }),
  ],
});
<summary>Firefox Experimental Manifest V3 </summary> There are two configurations an extension needs to make for experimental manifest V3 support:
  1. Background service workers are not supported, so you are required to use a background script.
  2. The use_dynamic_url property is not supported for web accessible resources. In the plugin options, set useDynamicUrlWebAccessibleResources to false:

       webExtension({
         ...
         useDynamicUrlWebAccessibleResources: false,
       }),
<summary>Devtools</summary> To add content to the browser dev tools, add `devtools_page` to your manifest
devtools_page: "src/entries/devtools/index.html",

Place a script devtools.js in public dir.

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
);

Then load the script from your devtools html which placed in 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>

Options

manifest

  • The manifest definition for your extension
  • All manifest property file names should be relative to the root of the project.

useDynamicUrlWebAccessibleResources (optional)

  • Type: boolean
  • Default: false
  • Adds the use_dynamic_url property to web accessible resources generated by the plugin
    • Caution: In Chrome 130, with this option enabled, importing a generated resource using chrome.runtime.getURL will not work (Chromium Issue)l

optimizeWebAccessibleResources (optional)

  • Type: boolean
  • Default: true
  • On build, in Manifest V3, merge web accessible resource definitions that have matching non-resource properties and dedupe and sort resources. In Manifest V2, sort web accessible resources.

additionalInputs (optional)

  • Type:

      type AdditionalInput =
        | string
        | {
            fileName: string;
            webAccessible?:
              | boolean
              | {
                  matches: string[];
                  extensionIds?: string[];
                  excludeEntryFile?: boolean;
                }
              | {
                  matches?: string[];
                  extensionIds: string[];
                  excludeEntryFile?: boolean;
                };
          };
    
      additionalInputs?: {
        scripts?: AdditionalInput[];
        html?: AdditionalInput[];
        styles?: AdditionalInput[];
      };
  • Additional input files that should be processed and treated as web extension inputs.

  • Useful for dynamically injected scripts or dynamically opened HTML pages.
  • The webAccessible option configures whether the input file and its dependencies are included in the manifest web_accessible_resources property. Defaults to true.
    • When set to true, defaults to:
        {
          matches: ['<all_urls>'],
          excludeEntryFile: false,
        }
    • The excludeEntryFile option prevents the entry file from being added as a web accessible resource. Defaults to false.
  • Example
      webExtension({
        manifest: ...,
        additionalInputs: {
          scripts: [
            'src/entries/webAccessibleScript.js', // defaults to webAccessible: true
            {
              fileName: 'src/entries/webAccessibleScript2.js',
              webAccessible: true,
            },
            {
              fileName: 'src/entries/privateScript.js', // entry file and dependencies are not web accessible
              webAccessible: false,
            },
            {
              fileName: 'src/entries/entryFileExcluded.js', // entry file is not web accessible and dependencies are
              webAccessible: {
                matches: ['<all_urls>'],
                excludeEntryFile: true,
              },
            },
          ],
        },
      })

Content Scripts

  • For HMR style support within shadow DOMs, use the addStyleTarget function to add the shadowRoot of your element as a style target:

    if (import.meta.hot) {
      const { addViteStyleTarget } = await import(
        "@samrum/vite-plugin-web-extension/client"
      );
    
      await addViteStyleTarget(appContainer);
    }
  • For builds, use the import.meta.PLUGIN_WEB_EXT_CHUNK_CSS_PATHS variable to reference an array of CSS asset paths associated with the current output chunk.

TypeScript

In an env.d.ts file, add the following type reference to define the plugin specific import.meta variables as well as plugin client functions:

/// <reference types="@samrum/vite-plugin-web-extension/client" />

Browser Support

The following requirements must be met by the browser:

  • Must support dynamic module imports made by web extension content scripts.
  • Must support import.meta.url

A sample of supported browsers:

| | Manifest V2 | Manifest V3 | | -------- | ----------- | -------------------------------------------------------------------------------------- | | Chromium | 64 | 91 | | Firefox | 89 | N/A (In development) |

The plugin will automatically default vite's build.target config option to these minimum browser versions if not already defined by the user.

For dev mode support in Manifest V3, Chromium version must be at least 110.

How it works

The plugin will take the provided manifest, generate rollup input scripts for supported manifest properties, then output an ES module based web extension.

This includes:

  • Generating and using a dynamic import wrapper script in place of original content scripts. Then, moving the original scripts to web_accessible_resources so they are accessible by the wrapper script. Needed because content scripts are not able to be loaded directly as ES modules.
    • This may expose your extension to fingerprinting by other extensions or websites. Manifest V3 supports a use_dynamic_url property that will mitigate this. This option is set for manifest V3 web accessible resources generated by this plugin.
  • Modifying Vite's static asset handling to maintain import.meta.url usages instead of rewriting to self.location. Needed so content script static asset handling can function correctly.
  • Modifying Vite's HMR client to add support for targeting specific elements as style injection locations. Needed to support HMR styles in shadow DOM rendered content.

Why this is a Vite specific plugin

The plugin relies on Vite to parse and handle html files in addition to relying on Vite's manifest generation in order to map generated files to the eventual extension manifest.

Development

This project uses pnpm for package management.

Lint

pnpm lint

Tests

pnpm test

Build

pnpm build

changelog

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

5.1.1 (2024-09-26)

Bug Fixes

  • use_dynamic_url with content scripts does not work in Chrome 130 (#145) (b014902)

5.1.0 (2023-12-12)

Features

Bug Fixes

  • only use the httpServer if it exists (#133) (aede4fa)

5.0.0 (2023-06-01)

⚠ BREAKING CHANGES

Check MIGRATION.md for migration instructions

  • drop vite 3 support, minimum version is now vite 4 (#99)
  • drop node 14 support, minimum version is now node 16 (#98)
  • throw an error when inputs have matching output identifiers (#103)
  • hmr: always use transformIndexHtml for HTML processing, remove devHtmlTransform option (#115)

Features

  • support Vite config.define properties in dev mode (#97) (c0edbab)

Bug Fixes

  • hmr: directory already exists error on server start (#108) (e177115)
  • hmr: location.reload/document errors in service worker (#100) (5527320)
  • hmr: readFile, writeFile not exported by fs-extra (#106) (c9c2ebf)
  • hmr: vite env client path is wrong in workspaces (#101) (c9eb6be)
  • shared output id error is triggered on same input/output pair (#107) (0c0a822)

  • devBuilder: always use transformIndexHtml for HTML processing (#115) (3e7da0c)

  • drop node 14 support, minimum version is now node 16 (#98) (79a3542)
  • drop vite 3 support, minimum version is now vite 4 (#99) (aa72014)
  • throw an error when inputs have matching output identifiers (#103) (f929057)

4.1.0 (2023-04-13)

Features

  • support hash and query properties in manifest HTML filenames (#92) (12950b1), closes #90

4.0.0 (2023-04-10)

⚠ BREAKING CHANGES

Check MIGRATION.md for migration instructions

  • The webAccessibleScripts option has been removed and replaced by the additionalInputs option. For similar functionality, move scripts to additionalInputs.scripts and html files to additionalInputs.html. Check the README or MIGRATION files for detailed usage instructions.
  • useDynamicUrlContentScripts option renamed to useDynamicUrlWebAccessibleResources
  • dev mode plugin HTML transforms are no longer applied by default. Use the devHtmlTransform option to enable if needed.
  • optimize web accessible resources (#89)

Features

Bug Fixes

  • react HMR HTML errors due to CSP in manifest V3 (#86) (49db181)
  • Input TypeScript file extensions not being correctly converted to .js in output manifest.json

3.1.1 (2023-02-25)

Bug Fixes

  • internal viteMetadata type conflicts with Vite (#83) (9043206)

3.1.0 (2023-02-05)

Features

  • content_scripts css property processing by Vite (#77) (84ff1ab)

Bug Fixes

  • DevBuilder’s output path should respect the root property of ViteConfig (#81) (9307b79)

3.0.0 (2023-01-03)

⚠ BREAKING CHANGES

  • dynamic imports in content scripts are broken (#71)

Features

  • don't create loader for web accessible scripts with no imports (#72) (8acfaec)
  • Vite 4 support (#70) (49330cd)

Bug Fixes

  • dynamic imports in content scripts are broken (#71) (fe888e4)
  • web accessible scripts with no loader have incorrect filename (#73) (5d04de4)

2.2.1 (2023-01-02)

Bug Fixes

  • getMetadataForChunk infinitely loops when parsing build output (#67) (6092362)
  • hmr not working since vite 3.2.3 (#69) (b49f05f)
  • node_modules dependencies shouldn't have dynamic imports modified (#68) (232b90f)

2.2.0 (2022-11-22)

Features

  • firefox experimental manifest V3 support (#63) (fd62c7d)

2.1.1 (2022-10-01)

Bug Fixes

  • improve the way CSP is modified in HMR mode (#54) (6143dfe)

2.1.0 (2022-09-26)

Features

  • generate loader files for web accessible scripts (#52) (da38880)

2.0.0 (2022-09-06)

⚠ BREAKING CHANGES

  • Vite 3 is now the minimum supported version of Vite

Features

Bug Fixes

  • include imports from web accessible scripts in manifest v3 (#41) (65d52f5)
  • make dynamic imports resolve relative to extension host (#37) (7948164)
  • manifest V3: correct matches property in web accessible resources (#47) (17d97d3)
  • manifest v3: web accessible resource match rewrite is broken (#48) (4e2ba91)

  • bump Vite to 3.0.2 (#36) (bdfa480)

1.0.2 (2022-04-24)

1.0.2-beta.1 (2022-04-24)

Bug Fixes

  • add /vite/client to optimizeDeps.exclude (#27) (119cbc2)

1.0.2-beta.0 (2022-04-24)

Bug Fixes

  • force /@vite/client to be external (#26) (9c11af5)

1.0.1 (2022-04-23)

Bug Fixes

  • vite-ignore /@vite/client import in client.js (#25) (4d0edc7)

1.0.0 (2022-04-08)

⚠ BREAKING CHANGES

  • import.meta.CURRENT_CONTENT_SCRIPT_CSS_URL has been replaced with import.meta.PLUGIN_WEB_EXT_CHUNK_CSS_PATHS. Minimum supported version of Vite is now 2.9.0

Features

  • add client types for plugin users (#11) (8b96fac)

Bug Fixes

  • multiple css dependencies in content scripts, shared css across chunks (#13) (c2dbe8f)

0.1.8 (2022-03-28)

Bug Fixes

  • devBuilder: add missing csp source for firefox (#10) (cb2f239)

0.1.7 (2022-02-18)

Features

  • dev: reprocess manifest HTML files on change (#7) (d643e5e)

0.1.6 (2022-02-13)

Features

  • dev: apply plugin html transforms, add CSP inline script hashes (#4) (44c10b0)

Bug Fixes

  • ensure dev server is set for dev builds, add object-src to dev CSP (#5) (056547c)
  • only set script hashes in manifest V2 CSP (#6) (ad3580d)

0.1.5 (2022-02-10)

Bug Fixes

  • background.html missing in dev mode (#2) (1fa4d47)

0.1.4 (2022-02-09)

Bug Fixes

0.1.3 (2022-01-06)

Bug Fixes

  • make manifest parsers use a copy of input manifest (2c0ab12)
  • normalize filenames on output manifest matching (b899410)

0.1.2 (2022-01-03)

Features

  • maintain existing build.target config if set (d75c9e1)

Bug Fixes

  • reference url using req object (ae04fa7)

0.1.1 (2022-01-03)

Bug Fixes

  • add missing breaks for build targets (6f2ff64)
  • update placeholder input to work with new vite input handling (91a5c29)

0.1.0 (2022-01-03)