Search code examples
typescriptvitechrome-extension-manifest-v3

Vite + Chrome Extension Manifest v3 - "Cannot use import statement outside a module" for inpage scripts


I created an extension based off https://github.com/Jonghakseo/chrome-extension-boilerplate-react-vite project. In manifest I set background type to module

 background: {
    service_worker: "background.js",
    type: "module",
  },

and in background service I dynamically create inpage content-scripts like so

 await chrome.scripting.registerContentScripts([
      {
        id: currInpageId,
        matches: ["file://*/*", "http://*/*", "https://*/*"],
        js: [`inpage-${inpageType}.js`],
        runAt: "document_start",
        allFrames: true,
        world: "MAIN",
      },
    ]);

inpage files are passed as individual inputs to vite.config

input: {
          ...inpageTypes.reduce(
            (acc, inpageType) => ({
              ...acc,
              [`inpage-${inpageType}`]: resolve(
                inpageDir,
                `inpage-${inpageType}.ts`
              ),
            }),
            {}
          ),
        },

but when I run the ext I get an error

Uncaught SyntaxError: Cannot use import statement outside a module

How can I resolve it?

Thanks!


Solution

  • As @wOxxOm suggested, I had to create 3 separate vite configs:

    • inpage config
    • content-script config
    • rest of the code config

    when for inpage and content-script, I set

    build: {
      emptyOutDir: false,
      ...
      rollupOptions: {
        output: {
          entryFileNames: "[name].js",
          inlineDynamicImports: true,
        }
      }
    }