vite: When using `import` inside classic worker, syntax error happens during dev but build success

Describe the bug

When import is used in classic worker, the following error happens during dev.

Uncaught SyntaxError: Cannot use import statement outside a module

But build works with it and the bundle seems to be correctly bundled.

According to the docs, import can be used inside classic worker if worker is imported with query suffixes. There is no mention about constructor type worker import. But if it is the recommended way, I think it would be good to support it too. Also it is useful for #8466.

https://github.com/vitejs/vite/issues/8466#issuecomment-1146655205 might be related.

Reproduction

https://stackblitz.com/edit/vitejs-vite-mhmcjy?file=main.js

System Info

stackblitz

Vite: 2.9.9, 3.0.0-alpha.9

Used Package Manager

npm

Logs

No response

Validations

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 10
  • Comments: 19 (13 by maintainers)

Commits related to this issue

Most upvoted comments

Following this issue. This is the biggest inhibitor to running workers with imports in dev mode with Firefox. I can’t be the only one who develops against Firefox, right?

Looks like Firefox 114 will support import within workers.


EDIT: Confirmed.

FF114 adds support for ECMAScript modules. What that means is that you can use the constructor {type: “module”} in worker/shared worker constructor, and use both import and import(). In Worklets you can call import. FF does not yet support modules in ServiceWorkers, but they also allow import only.

FF114 ECMAScript module support

so the issue asks for

  1. dynamic import support in classic worker (build mode)
  2. static import support in classic worker (dev mode) 😵

Some colleagues prefer Firefox for development and we would like to debug on FF as well.

This issue prevents development on Firefox for any project that uses Workers with imports.

Is there a way to tell vite to inline imports into the worker file during development?

dynamic import are supported in both classic and module worker. But static import are not supported in classic worker.

import w from 'foo.js?worker' build time is also module.

It is classic if worker.format is iife (stackblitz 3.0.0-alpha.9, though it is es when vite 2.9.9).

It seems './modules/module0.js' run as <script type="module"> in classic worker.

Files imported by static or dynamic import is treated as ESM (even if they are import from a classic worker/script).