Skip to content

Content Script ESM Support #357

Open

Description

@aklinker1

Feature Request

As discussed in #335, it is possible to load ESM content scripts using a dynamic import. The downside is that since it's async, the standard run_at option has basically no effect.

I propose adding a new option to defineContentScript: type: "module". Similar to the background's type: "module" option.

When WXT sees an async content script, it will load the script asynchronously using a dynamic import.

await import(
  /* @vite-ignore */
  browser.runtime.getURL("path/to/chunk/entrypoint.js")
);

Questions:

  • Does the run_at in the manifest make a difference in loading speed when using a dynamic import

    Jan 20, 2024: Slightly, we should respect it, and allow configuring it, with the knowledge that document_start doesn't work. See Content Script ESM Support #357 (comment)

  • Can async content scripts be bundled in one step alongside HTML entrypoints, or do they have to be separated into their own step? My concern here is mixing chunks with side-effects that only work in HTML pages

    Jan 20, 2024: I don't think this is an issue, it's only an issue for the background service worker where there's no window global

  • How will dev mode function and reload content scripts. What about main world content scripts, should those be grouped with the regular HTML file builds, or be in their own build step?

    Feb 2, 2024: Have not tested dev mode yet, but I am building the ESM background script with the other extension pages, so I'll do the same with isolated world content scripts. Main world content scripts will be combined with the sandbox pages since those don't have access to the browser APIs, like sandbox pages.

  • Should type: "module" be the default value? It works well with the default run_at: "document_idle", and will likely provide a much better dev experience.

    Jan 21, 2024: If dev mode works well, yes, it will be the default.

    Feb 2, 2024: Initially, I'm going to make this an opt-in just like the background's type: "module". If it's working well for people, I'll try and make the the default before v1.0.

Is your feature request related to a bug?

#335

What are the alternatives?

No real alternatives to the feature as a whole. Instead of adding a new field, we could use runAt: "async", but that wouldn't provide a way to set the actual run_at in the manifest. That said, the run_at doesn't really matter, it can cause the browser to import the script earlier, but the code will never run before the DOMContentLoaded event.

Additional context

CC @yunsii

This will fix: #270

Activity

  1. added this to the v1.0 milestone on Jan 18, 2024
  2. yunsii commented on Jan 19, 2024

    @yunsii
    Contributor

    This feature is really nice, I am exploring how to implement HMR in content script like CRXJS, it is really a magic.

  3. aklinker1 commented on Jan 19, 2024

    @aklinker1
    MemberAuthor

    I've switch my proposal to use type: "module" instead of runAt: "async".


    @yunsii I'd like to structure the outputs like this:

    .output/
      <target>/
        chunks/
          ...
        content-scripts/
          <name>.js
          <name>-loader.js
    

    We may need to include the hash in dev mode to the non-loader file for HMR to work, I'm not sure.

    At a minimum, the loader would look something like this:

    import(
      /* @vite-ignore */
      browser.runtime.getURL("/content-scripts/<name>.js")
    );

    I'm also not sure where we need to call the main function of the content script. Inside the <name>.js like the above loader would do, or inside the <name>-loader.js, like this:

    const { default } = await import(
      /* @vite-ignore */
      browser.runtime.getURL("/content-scripts/<name>.js")
    );
    default.main(...);

    If I remember correctly, dynamically imported modules don't have access to the chrome or browser global, so we may need to use the second example, and actually run the main function of the content script inside the loader, which it has access to those globals.

  4. changed the title [-]"async" content script support[/-] [+]Content Script ESM Support[/+] on Jan 19, 2024
  5. yunsii commented on Jan 20, 2024

    @yunsii
    Contributor
  6. aklinker1 commented on Jan 20, 2024

    @aklinker1
    MemberAuthor

    Cool, thanks for researching this! If both work, we'll go with whatever option makes the most sense during the implementation.

  7. yunsii commented on Jan 20, 2024

    @yunsii
    Contributor

    we'll go with whatever option makes the most sense during the implementation.

    What's the meaning? I do not understand exactly.

  8. aklinker1 commented on Jan 20, 2024

    @aklinker1
    MemberAuthor

    Did some testing with the run_at field. Behaved exactly as I expected. It could be useful to set the run_at field. For ecxample, with document_start you load your script a little bit earlier, but the code will never run before the DOMContentLoaded event, unlike without a dynamic import.

    esm-run-at-testing.zip

    Screenshot 2024-01-19 at 11 40 07 PM
  9. aklinker1 commented on Jan 20, 2024

    @aklinker1
    MemberAuthor

    we'll go with whatever option makes the most sense during the implementation.

    What's the meaning? I do not understand exactly.

    @yunsii Between the two options (running main inside the imported file, or running main inside the loader), since both work, we can use either one in WXT. So whichever option is easier to do while implementing this feature, we'll go with.

  10. aklinker1 commented on Jan 20, 2024

    @aklinker1
    MemberAuthor

    Also, for future reference, here are the minimum requirements to get ESM content scripts working:

    1. Import statements must include the file extension
      This does not work:
      - import { logId } from './utils/log';
      This works:
      + import { logId } from './utils/log.js';
    2. All imported files (chunks and non-loader entrypoints) must be listed in web_accessible_resources
       {
         "matches": [...],
         "resources": ["content-scripts/<name>.js", "chunks/*"]
       }

    Here's a minimal example with an ESM service worker and content script sharing the ES module utility.

    minimal-esm-chrome-extension.zip

  11. yunsii commented on Jan 20, 2024

    @yunsii
    Contributor

    So it means that document_start and document_idle can use type: "module"?

  12. aklinker1 commented on Jan 20, 2024

    @aklinker1
    MemberAuthor

    So it means that document_start and document_idle can use type: "module"?

    You can use all three run_at values (document_start, document_end, and document_idle) with type: "module". But only document_idle will behave the same way with or without type: "module"

  13. yunsii commented on Jan 20, 2024

    @yunsii
    Contributor

    Did some testing with the run_at field. Behaved exactly as I expected. It could be useful to set the run_at field. For ecxample, with document_start you load your script a little bit earlier, but the code will never run before the DOMContentLoaded event, unlike without a dynamic import.

    esm-run-at-testing.zip

    Screenshot 2024-01-19 at 11 40 07 PM

    I see, with type: "module", this means all run_at values can work, but dynamic imports with document_start and document_end have to wait until the proper timing to run?

  14. aklinker1 commented on Jan 20, 2024

    @aklinker1
    MemberAuthor

    Yup, exactly!

  15. 23 remaining items

  16. yunsii commented on Aug 17, 2024

    @yunsii
    Contributor

    It means we can use dynamic import manually anywhere now? the dynamic import modules will not be bundle into the entry file?

  17. aklinker1 commented on Aug 17, 2024

    @aklinker1
    MemberAuthor

    @yunsii no, WXT will never produce code-split ESM by itself.

    This line tells vite to not analyze or bundle the dynamic import, and leave it as-is in the final output.

    https://github.com/wxt-dev/examples/blob/main/examples%2Fesm-content-script-ui%2Fentrypoints%2Fcontent%2Findex.ts#L4-L7

    Then you are then responsible for making sure the imported file exists, which is done with a custom vite build here:

    https://github.com/wxt-dev/examples/blob/main/examples%2Fesm-content-script-ui%2Fmodules%2Fesm-builder.ts#L32

  18. yunsii commented on Aug 18, 2024

    @yunsii
    Contributor

    I see, with WXT Reusable Modules to custom build esm modules and then import them manually.

    But it still not easy to use, why not integrated directly by WXT?

  19. aklinker1 commented on Aug 18, 2024

    @aklinker1
    MemberAuthor

    Hmm, I got it stuck in my head that this issue was about HMR, but if we ignore that and continue to do separate, code-split enabled builds with reloads like content scripts work today... It might be possible to implement a generic solution. Let me think on this more.

  20. gabrielgrant commented on Feb 12, 2025

    @gabrielgrant

    Any update on this?

  21. aklinker1 commented on Feb 13, 2025

    @aklinker1
    MemberAuthor

    Any update on this?

    Not a priority for me until v1.0 is out. The tradeoff of not respecting run_at means this specific feature has no real value to me personally, and there is a way to manually create a code-split content script. I will add this eventually, but not right now.

  22. rxliuli commented on Mar 3, 2025

    @rxliuli
    Contributor

    I still want a code splitting script, especially in dev mode, which is very useful for large plugins. For example, my content-script is over 16+M uncompressed right now, which makes hmr very, very slow. I guess chunk split would help.

    Image
  23. kirankunigiri commented on Jan 14, 2026

    @kirankunigiri

    Hi! Wondering if this this going to be revisited anytime soon? Saving any content script file in my project takes 5+ seconds to reload and it's basically unusable for larger projects.

  24. rxliuli commented on Jan 15, 2026

    @rxliuli
    Contributor

    For anyone tired of excessively long build times, try upgrading wxt + vite and using the beta version of rolldown. In my testing, it reduced build time by nearly 10x (35s => 3s). Unfortunately, my entire extension codebase has become rotten, containing many outdated dependencies, and I have to consider a complete rewrite to use it.

  25. added this to the v1.1 milestone on Feb 11, 2026
  26. aklinker1 commented on Feb 11, 2026

    @aklinker1
    MemberAuthor

    Hi! Wondering if this this going to be revisited anytime soon? Saving any content script file in my project takes 5+ seconds to reload and it's basically unusable for larger projects.

    I meant to have this in the v1.1 milestone, added. I am putting this off until v1.0 is released. No ETA on that right now.

  27. oyzamil commented on Apr 18, 2026

    @oyzamil
    Contributor

    I still want a code-splitting script, especially in dev mode, which is very useful for large plugins. For example, my content script is over 16+M uncompressed right now, which makes HMR very, very slow. I guess chunk split would help.

    Image

    Maybe this custom hook can help you:

    // wxt.config.ts
    import { defineConfig } from 'wxt';
    
    export default defineConfig({
      hooks: {
        'vite:build:extendConfig': (entrypoints, config) => {
          const hasHtmlEntrypoint = entrypoints.some(
            (e) => e.type === 'popup' || e.type === 'options'
          );
          if (!hasHtmlEntrypoint) return;
    
          config.build ??= {};
          config.build.rollupOptions ??= {};
          config.build.rollupOptions.output ??= {};
    
          // Rename auto-generated shared chunks with a function
          // @ts-ignore
          config.build.rollupOptions.output.chunkFileNames = (chunkInfo) => {
            // Named chunks from codeSplitting groups already have clean names
            // (vendor-react, vendor-antd, vendor) — keep those as-is
            const name = chunkInfo.name ?? 'chunk';
            return `chunks/${name}-[hash].js`;
          };
    
          // @ts-ignore
          config.build.rollupOptions.output.codeSplitting = {
            groups: [
              { name: 'vendor-react', test: /node_modules[\\/]react/, priority: 30 },
              { name: 'vendor', test: /node_modules/, priority: 10 },
              // Give your shared app code a stable name too
              { name: 'shared', minShareCount: 2, priority: 5 },
            ],
          };
        },
      },
    });
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

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions