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

1

8

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!

Cleland answered 5/10, 2023 at 9:31 Comment(5)
Assuming the error is in the web page and not in the service worker, you need to configure the type of output produced by vite through some option (I don't know which though).Commonage
it is indeed returned from the webpage, since the error originate in content script and not the background service worker. wdym @wOxxOm? what should I configure? the only thing I thought about was making the imports inline, but it's unavailable when you have multiple inputs as I do.Cleland
It's probably something about the runtime chunk, which you shouldn't use, i.e. every file should be entirely self-sufficient and not share anything.Commonage
Yeah I suspected as much, but I'm afraid it will break HMR and all the things I get from vite :(Cleland
HMR doesn't work with content scripts in the page anyway.Commonage
C
2

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,
    }
  }
}
Cleland answered 9/10, 2023 at 8:0 Comment(2)
I don't understand, can you explain further? How are you creating 3 separate vite config files? How are they configured, how are you building?Electuary
This answer is terribly vague.Infamy

© 2022 - 2024 — McMap. All rights reserved.