Skip to content

Modules - API Proposal #665

Closed

Description

@aklinker1

Feature Request

Create build-time "modules" that can configure and inject shared code.

// modules/analytics.ts
export default defineWxtModule<AnalyticsModuleOptions>({
  meta: {
    // NPM package name, or inferred from filename: "modules/*.ts"
    // name: "wxt-module-analytics",
    // The key in `wxt.config` that holds your module options
    configKey: "analytics",
    // Compatibility constraints
    compatibility: {
      // Semver version of supported nuxt versions
      wxt: "^0.18.0",
    },
  },
  // Default configuration options for your module, can also be a function returning those
  defaults: {},
  // Shorthand sugar to register WXT hooks
  hooks: {},
  setup(moduleOptions, wxt) {
    // ...
  },
});

To include a NPM package as a module:

// wxt.config.ts

export default defineConfig({
  modules: ["analytics"], // Finds package named "wxt-module-analytics"
});

The design of the modules system is based on Nuxt's modules system. Basically, everything revolves around using hooks to modifying the build process to achieve some effect, either injecting code, changing vite config, adding entrypoints, or something else.

Modules should be able to:

  1. Based on the module definition, add types to the InlineConfig interface to allow adding type-safe config
    // .wxt/plugins.d.ts
    module "wxt" {
      export interface InlineOptions {
        analytics: import("wxt-module-analytics").ModuleOptions
      }
    }
  2. Provide a way to inject code that will be ran in an entrypoins (background, popup, etc) and access results
    import { injectJs, addScriptElement } from 'wxt/modules';
    
    export default defineWxtModule({
      // ...
      setup(_, wxt) {
       injectJs(async (entrypoint) => {
         // Return undefined to not inject code
         if (entrypoint.type !== "content-script") return;
    
         return {
           imports: "import { init } from 'wxt-module-analytics/client'",
           code: `const analytics = init("${entrypoint.name}")`,
           provide: ["analytics"],
         }
       });
       addScriptElement((entrypoint) => {
         if (entrypoint.name !== "popup") return;
         return `<script type="module" src="wxt-module-analytics/client/init"></script>`
       });
      },
    });
  3. Add automatic imports
    import { addAutoImports } from 'wxt/modules';
    
    export default defineWxtModule({
      // ...
      imports: [
        { from: "wxt-module-analytics/client", name: "reportEvent" },
      ],
    });
  4. Add entrypoints
    import { addEntrypoint } from 'wxt/modules';
    
    export default defineWxtModule((wxt) => {
      addEntrypoint({
        type: "content-script",
        name: "some-analytics-script",
        options: {
          matches: "*://*/*",
          // ...
        },
        // ...
      })
    });

    Might want to change this to only allow "pre-bundled" entrypoints so these don't effect build time, and are just copied into the output directory.

  5. Modify vite config (add plugins or override fields)
    import { addViteConfig } from 'wxt/modules';
    
    export default defineWxtModule((wxt) => {
      addViteConfig((entrypoint) => ({
        plugins: [...],
      }))
    });

Some examples of modules:

  • Analytics - configure and expose APIs for reporting analytic events for different services (GA, umami, etc)
  • Bug reporting - configure and expose APIs for reporting errors (sentry, bugsnag, etc)
  • Changelog generator - When the extension updates, open a changelog.html file based off a CHANGELOG.md file or github releases
  • ...

This is extremely useful when you need to reuse logic between extensions that whose setup spans multiple entrypoints. If you were to use a shared library for sharing this type of code, you would have to setup the library in all the different entrypoints, which can be annoying if you maintain multiple extensions or the setup is complex.

Is your feature request related to a bug?

N/A

Additional context

Add any other context or screenshots about the feature request here.

Activity

  1. pinned this issue on May 21, 2024
  2. changed the title [-]Plugins[/-] [+]Plugins (API discussion)[/+] on May 21, 2024
  3. aklinker1 commented on May 21, 2024

    @aklinker1
    MemberAuthor

    Edit. These are actually "modules", not "plugins", according to Nuxt verbiage. These operate at build-time, not runtime. So I'm renaming this issue: "Plugins (API discussion)" → "Modules (API discussion)"

  4. changed the title [-]Plugins (API discussion)[/-] [+]Modules (API discussion)[/+] on May 21, 2024
  5. changed the title [-]Modules (API discussion)[/-] [+]Modules - API Proposal[/+] on May 21, 2024
  6. aklinker1 commented on May 21, 2024

    @aklinker1
    MemberAuthor

    I need to figure out a better way of transforming the JS/TS code to add custom lines. For example, we need to be able to add imports, call functions, and set the results of those functions in some kind of global scope so they can be accessed later by the client.

       injectJs(async (entrypoint) => {
         // Return undefined to not inject code
         if (entrypoint.type !== "content-script") return;
    
         return {
           imports: "import { init } from 'wxt-module-analytics/client'",
           code: `const analytics = init("${entrypoint.name}")`,
           provide: ["analytics"],
         }
       });

    If we just use regex to replace code, it will result in Vite complaining about source maps not aligning.

  7. aklinker1 commented on May 21, 2024

    @aklinker1
    MemberAuthor

    I suppose one option would be to add an import at the top of all JS entrypoints, like this:

    // .output/chrome-mv3/background.js
    import initModules from 'virtual:wxt-modules'
    import definition from '...';
    
    try {
      const provided = initModules();
      definition.main(provided);
    } catch (err) {
      // ...
    }

    Then use a vite plugin to load custom code for the virtual:wxt-modules import. In the example above, this module's content might look like this:

    import { init } from 'wxt-module-analytics/client';
    
    export function initModules() {
      const analytics = init("background");
    
      return {
        analytics
      }
    }

    This would get around the issues with transforming code. But in this case, it's suddenly looking quite a bit like a plugin-API, with the need for runtime code... Do I have to do both at the same time?

  8. davestewart commented on Jun 3, 2024

    @davestewart
    Contributor

    Hey @aklinker1.

    Congrats on what looks like a really solid framework!

    I'm also a Nuxt user and long-time extension developer.

    Nuxt's Layers are also a nice way to think about adding custom functionality. They're a little bit less manual than modules, in the way that (I think) they are effectively a module which processes a layer as a mini-application, with certain expectations of what a "layer" will contain.

    I wrote about it here:

    I remember somewhere is mentioned that the main app in a Nuxt build is useNuxt().options._layers[0] so in effect, everything is a layer. Here is an example from the Nuxt Image lib:

    FWIW, the main extension I work on is split up as application-specific "modules" and I stitch these together manually through imports. I'm looking at migrating at the moment from my existing MV2/Webpack setup, but starting by migrating a much simpler extension to get the feel.

    Anyway, happy to contribute to this conversation once I'm more familiar with your framework.

  9. aklinker1 commented on Jun 3, 2024

    @aklinker1
    MemberAuthor

    @davestewart thanks for the idea! Layers is definitely something I want to support at some point. I'm starting with modules because I already have hooks setup, and that's really all that's needed. The main thing that I see modules providing over layers is the ability to modify project entrypoints, like injecting analytics or crash reporting. I don't think that's something layers is capable of.

    Though I guess you could add a plugin to a layer which might accomplish similar things... I'm currently thinking through what a plugin-like API would look like with WXT, since it's not really 1-to-1 with Nuxt.

    Need to answer questions like:

    • Where do plugin files go?
    • How do you decide which entrypoints a plugin effects?
    • How does WXT actually include and execute plugin code at runtime?

    For reference, in Nuxt, modules are executed during the build while plugins are executed at runtime on server startup.

    Now that I think about it... How do plugins work on the client side? Do they work? Do they use some .client.ts suffix to denote what the plugin effects? I need to do more research into Nuxt's implementation. Might help answer some of those questions above.

  10. aklinker1 commented on Jun 9, 2024

    @aklinker1
    MemberAuthor

    Alright, settled on the plan for adding code to JS entrypoints.

    1. Register a plugin
      export default defineWxtModule((wxt) => {
         registerPlugin(wxt, (entrypoint) => true, "some-plugin");
       });

      Second argument lets you filter which type of entrypoint the plugin is loaded in.

    2. In the plugin, export a default plugin object:
      // some-plugin
      export default defineWxtPlugin(() => {
        // Do something
      });
    3. Inside WXT, all plugins will be called before the entrypoint's main options:
      // virtual:wxt-background-entrypoint
      import definition from 'your-entrypoint';
      import { initPlugins } from 'virtual:wxt-plugins';
      
      try {
        initPlugins();
        definition.main();
      } catch (err) {
        // ...
      }
      // virtual:wxt-plugins
      import plugin1 from 'some-plugin'
      
      export function initPlugins() {
        plugin1.main();
      }

    Right now, since plugins won't be user-defined by adding files in a plugins folder, I'm not going to worry about ordering, other than respecting the order you call registerPlugin in.

    Will need to figure out how to use local files for plugins, but I'm not too worried about that, don't need to consider it at this planning stage.

  11. added this to the v1.0 milestone on Jun 11, 2024
  12. aklinker1 commented on Jun 12, 2024

    @aklinker1
    MemberAuthor

    Released building blocks and basic implementation in v0.18.5.

    Will be providing more examples and actual modules soon. For now, refer to the meager docs: https://wxt.dev/guide/go-further/reusable-modules.html

  13. unpinned this issue on Jun 13, 2024
  14. davestewart commented on Dec 11, 2025

    @davestewart
    Contributor

    For anyone interested, I wrote a WXT Layers module, thanks to @aklinker1's awesome work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions