1.0.2-beta.1 • Published 2 years ago

@solar-republic/vite-plugin-web-extension v1.0.2-beta.1

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

@samrum/vite-plugin-web-extension

npm version ci

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

Features

  • Manifest V2 & V3 Support
  • Completely ES module based extensions
    • Including content scripts!
  • Vite based html and static asset handling
    • Including content scripts!
  • HMR support for all manifest properties (excluding Manifest V3)
    • Including content scripts! (excluding Firefox)
  • HMR support for CSS styles in content scripts
    • Including shadow DOM rendered content!

Quick Start

Create a new Vite web extension project

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

Supports choice of Manifest, TypeScript, and framework (Vanilla, Vue, React, Preact, Svelte)

Manual Install

Requires Vite 2.9+

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

Usage

Vite Config

  • All manifest file names should be relative to the root of the project.

Examples

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

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.

Web Accessible Scripts

This plugin will detect scripts under web_accessible_resources and apply the same transformations to them as your content scripts. This can be very useful for developers who need to inject scripts into a live page, usually to mutate or extend properties on the window object.

By default, it will include scripts matching /\.([cem]?js|ts)$/, but you can provide custom filter options in the call to webExtension(options?: ViteWebExtensionOptions):

type Pattern = string | RegExp | Array<string | RegExp>;

interface ViteWebExtensionOptions {
  manifest: chrome.runtime.Manifest;

  webAccessibleScripts?: {
    include?: Pattern;
    exclude?: Pattern;
    options?: {
      resolve?: string | false | null;
    };
  };
}

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 V2Manifest V3
Chromium6491
Firefox89N/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.

Devtools

If you want to create a developer tools, add devtools_page in 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>

How it works

The plugin will take the provided manifest, parse rollup input scripts from all 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