chrome-extension-boilerplate-react-vite: TypeError: Failed to fetch dynamically imported module

I’m getting the following error when trying to inject some HTML via this chrome extension boilerplate:

Uncaught (in promise) TypeError: Failed to fetch dynamically imported module: chrome-extension://{my-extension-id}/assets/js/index.js

It only happens about 10% of the time, which is strange. I think it has something to do with the Vite configuration, although, it is difficult to debug with it only happening occasionally.

Might it have something to do with the customDynamicImport() function, or some other custom configuration of this boilerplate? Any help would be appreciated!

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Comments: 15 (9 by maintainers)

Commits related to this issue

Most upvoted comments

I found customDynamicImport doesn’t work with await import, here is error:

src/pages/background/index.js:7681:16: ERROR: Expected ":" but found "dynamicImport"

Expected ":" but found "dynamicImport"
7679|                  const { FewShotPromptTemplate } = await
7680|          {
7681|            const dynamicImport = (path) => import(path);
   |                  ^
7682|            dynamicImport(
7683|            '../../../assets/js/few_shot.js')};

and this will resolve my problem

  1. update vite >= 3.2
  2. add modulePreload: false in vite.config.ts build part
  3. change custom-dynamic-import.ts:
import type { PluginOption } from "vite";

export default function customDynamicImport(): PluginOption {
  return {
    name: "custom-dynamic-import",
    renderDynamicImport({ moduleId }) {
      if (!moduleId.includes("node_modules")) {  // <- dont modify any import from node_modules
        if (process.env.__FIREFOX__) {
          return {
            left: `
          {
            const dynamicImport = (path) => import(path);
            dynamicImport(browser.runtime.getURL('./') + 
            `,
            right: ".split('../').join(''))}",
          };
        }
        return {
          left: `
          {
            const dynamicImport = (path) => import(path);
            dynamicImport(
            `,
          right: ")}",
        };
      }
      return {
        left: "import(",
        right: ")",
      };
    },
  };
}