"Cannot use import statement outside module" when registering service worker from script type=module

534 Views Asked by At

I've searched for existing answers regarding extensions and service workers, like Workbox service worker: Cannot use import statement outside a module and the answers are either vague "it should theoretically work now" hence asking here, with a minimal example.

I am developing a Chrome extension, and the extension, including its manifest, currently works.

However when I add the following to service-worker.js

import { log } from "./service-worker-helpers.js";

...where service-worker-helpers.js is just:

export const log = console.log.bind(console);

I see the following behaviour:

  • Loading the extension parses the service worker, run the Install event. etc, with zero errors reported on the console.
  • Clicking the popup (which registers the service worker) fails with:

Cannot use import statement outside a module

enter image description here

I understand the error - Chrome wants me to be using an ES6 module to use import

However the popup itself is using script type="module":

<script type="module" src="/assets/index.07165314.js"></script>

I am also using ES6 modules for my service worker - which is why loading the module (which seems to parse the service worker file) works:

"background": {
  "service_worker": "service-worker.js",
  "type": "module"
},

How can I register a background script that uses ES6 modules?

0

There are 0 best solutions below