npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ugurkellecioglu/vite-plugin-web-extension

v5.1.3

Published

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

Downloads

44

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

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"],
        },
      },
    }),
  ],
});

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",
        },
      },
    }),
  ],
});
  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,
      }),
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