Repository navigation
Closed
Labels
Description
Describe the bug
I have my project set up where I have an index file that exports everything in the folder. This is so I can solve a circular dependency.
When I created a web worker, I had it import from the index file. One of these files in the index directly imported the web worker using ?worker. This worked fine in development. When I went to build, however, Vite seemed to get stuck in an infinite loop and only stopped when it ran out of memory.
Reproduction
https://github.com/hf02/vite-infinite-build Much simpler reproduction, thanks to @zxch3n: https://stackblitz.com/edit/vitejs-vite-u59lcw?file=worker.js
System Info
System:
OS: Windows 10 10.0.22000
CPU: (16) x64 AMD Ryzen 7 3700X 8-Core Processor
Memory: 9.38 GB / 15.95 GB
Binaries:
Node: 16.14.0 - ~\AppData\Local\nvs\default\node.EXE
npm: 8.3.1 - ~\AppData\Local\nvs\default\npm.CMD
Browsers:
Edge: Spartan (44.22000.120.0), Chromium (98.0.1108.56)
Internet Explorer: 11.0.22000.120Used Package Manager
pnpm
Logs
PS C:\Users\user\Desktop\vite-project> # i replaced my windows username with a generic "user"
PS C:\Users\user\Desktop\vite-project> pnpx vite build --debug
vite:config no config file found. +0ms
vite:config using resolved config: {
vite:config root: 'C:/Users/user/Desktop/vite-project',
vite:config base: '/',
vite:config mode: 'production',
vite:config configFile: undefined,
vite:config logLevel: undefined,
vite:config clearScreen: undefined,
vite:config build: {
vite:config target: [ 'es2019', 'edge88', 'firefox78', 'chrome87', 'safari13.1' ],
vite:config polyfillModulePreload: true,
vite:config outDir: 'dist',
vite:config assetsDir: 'assets',
vite:config assetsInlineLimit: 4096,
vite:config cssCodeSplit: true,
vite:config cssTarget: [ 'es2019', 'edge88', 'firefox78', 'chrome87', 'safari13.1' ],
vite:config sourcemap: false,
vite:config rollupOptions: {},
vite:config minify: 'esbuild',
vite:config terserOptions: {},
vite:config write: true,
vite:config emptyOutDir: null,
vite:config manifest: false,
vite:config lib: false,
vite:config ssr: false,
vite:config ssrManifest: false,
vite:config reportCompressedSize: true,
vite:config chunkSizeWarningLimit: 500,
vite:config watch: null,
vite:config commonjsOptions: { include: [Array], extensions: [Array] },
vite:config dynamicImportVarsOptions: { warnOnError: true, exclude: [Array] }
vite:config },
vite:config configFileDependencies: [],
vite:config inlineConfig: {
vite:config root: undefined,
vite:config base: undefined,
vite:config mode: undefined,
vite:config configFile: undefined,
vite:config logLevel: undefined,
vite:config clearScreen: undefined,
vite:config build: {}
vite:config },
vite:config resolve: { dedupe: undefined, alias: [ [Object], [Object] ] },
vite:config publicDir: 'C:\\Users\\user\\Desktop\\vite-project\\public',
vite:config cacheDir: 'C:\\Users\\user\\Desktop\\vite-project\\node_modules\\.vite',
vite:config command: 'build',
vite:config isProduction: true,
vite:config plugins: [
vite:config 'alias',
vite:config 'vite:modulepreload-polyfill',
vite:config 'vite:resolve',
vite:config 'vite:html-inline-proxy',
vite:config 'vite:css',
vite:config 'vite:esbuild',
vite:config 'vite:json',
vite:config 'vite:wasm',
vite:config 'vite:worker',
vite:config 'vite:worker-import-meta-url',
vite:config 'vite:asset',
vite:config 'vite:define',
vite:config 'vite:css-post',
vite:config 'vite:watch-package-data',
vite:config 'vite:build-html',
vite:config 'commonjs',
vite:config 'vite:data-uri',
vite:config 'rollup-plugin-dynamic-import-variables',
vite:config 'vite:asset-import-meta-url',
vite:config 'vite:build-import-analysis',
vite:config 'vite:esbuild-transpile',
vite:config 'vite:terser',
vite:config 'vite:reporter',
vite:config 'vite:load-fallback'
vite:config ],
vite:config server: {
vite:config preTransformRequests: true,
vite:config fs: { strict: true, allow: [Array], deny: [Array] }
vite:config },
vite:config preview: {
vite:config port: undefined,
vite:config strictPort: undefined,
vite:config host: undefined,
vite:config https: undefined,
vite:config open: undefined,
vite:config proxy: undefined,
vite:config cors: undefined,
vite:config headers: undefined
vite:config },
vite:config env: { BASE_URL: '/', MODE: 'production', DEV: false, PROD: true },
vite:config assetsInclude: [Function: assetsInclude],
vite:config logger: {
vite:config hasWarned: false,
vite:config info: [Function: info],
vite:config warn: [Function: warn],
vite:config warnOnce: [Function: warnOnce],
vite:config error: [Function: error],
vite:config clearScreen: [Function: clearScreen],
vite:config hasErrorLogged: [Function: hasErrorLogged]
vite:config },
vite:config packageCache: Map(0) { set: [Function (anonymous)] },
vite:config createResolver: [Function: createResolver],
vite:config optimizeDeps: {
vite:config esbuildOptions: { keepNames: undefined, preserveSymlinks: undefined }
vite:config },
vite:config worker: {
vite:config format: 'iife',
vite:config plugins: [
vite:config [Object], [Object], [Object],
vite:config [Object], [Object], [Object],
vite:config [Object], [Object], [Object],
vite:config [Object], [Object], [Object],
vite:config [Object], [Object], [Object],
vite:config [Object], [Object], [Object],
vite:config [Object], [Object], [Object],
vite:config [Object], [Object], [Object]
vite:config ],
vite:config rollupOptions: {}
vite:config }
vite:config } +5ms
vite v2.8.4 building for production...
transforming (85241) src\lib\worker\theWorker.ts
<--- Last few GCs --->
[1580:000002AACF9E4580] 152266 ms: Mark-sweep 3980.6 (4139.2) -> 3968.6 (4141.2) MB, 1286.2 / 0.0 ms (average mu = 0.131, current mu = 0.080) task scavenge might not succeed
[1580:000002AACF9E4580] 153712 ms: Mark-sweep 3982.3 (4141.4) -> 3970.8 (4143.4) MB, 1333.3 / 0.0 ms (average mu = 0.105, current mu = 0.078) task scavenge might not succeed
<--- JS stacktrace --->
FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
1: 00007FF63F237B7F v8::internal::CodeObjectRegistry::~CodeObjectRegistry+114079
2: 00007FF63F1C4546 DSA_meth_get_flags+65542
3: 00007FF63F1C53FD node::OnFatalError+301
4: 00007FF63FAFB29E v8::Isolate::ReportExternalAllocationLimitReached+94
5: 00007FF63FAE587D v8::SharedArrayBuffer::Externalize+781
6: 00007FF63F988C4C v8::internal::Heap::EphemeronKeyWriteBarrierFromCode+1468
7: 00007FF63F9958F9 v8::internal::Heap::PublishPendingAllocations+1129
8: 00007FF63F9928CA v8::internal::Heap::PageFlagsAreConsistent+2842
9: 00007FF63F985529 v8::internal::Heap::CollectGarbage+2137
10: 00007FF63F935A95 v8::internal::IndexGenerator::~IndexGenerator+22165
11: 00007FF63F15607F std::basic_ostream<char,std::char_traits<char> >::operator<<+80079
12: 00007FF63F154896 std::basic_ostream<char,std::char_traits<char> >::operator<<+73958
13: 00007FF63F29708B uv_async_send+331
14: 00007FF63F29681C uv_loop_init+1292
15: 00007FF63F2969BA uv_run+202
16: 00007FF63F265825 node::SpinEventLoop+309
17: 00007FF63F17CE83 v8::internal::Isolate::stack_guard+53827
18: 00007FF63F1FA40C node::Start+220
19: 00007FF63F01894C RC4_options+348236
20: 00007FF64007FE68 v8::internal::compiler::RepresentationChanger::Uint32OverflowOperatorFor+14472
21: 00007FF9B1D354E0 BaseThreadInitThunk+16
22: 00007FF9B360485B RtlUserThreadStart+43
PS C:\Users\user\Desktop\vite-project>Validations
- Follow our Code of Conduct
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
- Make sure this is a Vite issue and not a framework-specific issue. For example, if it's a Vue SFC related bug, it should likely be reported to https://github.com/vuejs/core instead.
- Check that this is a concrete bug. For Q&A open a GitHub Discussion or join our Discord Chat Server.
- The provided reproduction is a minimal reproducible example of the bug.
Reacted by Martin Schuhfuss, gotjoshua, Tony, Zixuan Chen, 年糕小豆汤, Frans Lee, Samuel Bolduc, Orhun Özer, Lehoczky Zoltán, Johannes Schickling and 3 more
Reacted by gotjoshua, Tony, Jamie, Tjeerd Bakker and John L. Armstrong IV
Activity
gotjoshua commentedon Mar 16, 2022
i have nearly the same problem and wondering if anyone has a workaround in mind...
gotjoshua commentedon Mar 16, 2022
I found a partial workaround to at least prevent the infinite loop and get a build output:
in vite.config.ts :
this avoids the loop during the transforming step, but does not transpile the webworker. rather it creates a single line file with
zxch3n commentedon May 10, 2022
I have a simplified reproduction of this infinite build https://stackblitz.com/edit/vitejs-vite-oqqjnr?file=worker.js,main.js,package.json&terminal=dev
hf02 commentedon May 10, 2022
Thanks for the much simpler reproduction. However, this may be a different bug? Instead of Vite showing
transforming (1) worker.jsand counting, it gets stuck on it.I forked your project. using
import()in worker.js instead. This fully reproduces the bug: https://stackblitz.com/edit/vitejs-vite-u59lcw?file=worker.jszxch3n commentedon May 10, 2022
I guess they are the same under the hook after this change
vite/packages/vite/CHANGELOG.md
Line 444 in 77865b4
iamcco commentedon Jun 28, 2022
Pyrolistical commentedon Aug 18, 2022
I also ran into this while trying to create a single file typed web worker. https://stackblitz.com/edit/vitejs-vite-9zt7v2?file=src/worker.ts
It works in dev but goes into a infinite loop during build.
What I was trying to do is build something like https://nodejs.org/api/worker_threads.html, where the script for both the client and the worker can be in the same file.
This is desirable in TypeScript in order align the type of data passed into the worker from the client.
Before this gets resolved, I now have to split up my worker into multiple files.
fixed build failure caused by vitejs/vite#7015
john-landgrave commentedon Nov 2, 2022
I am running into the same issue. This is particularly in a Vue project and my initial solve was to use inversion of control by having the module which was originally calling
new Worker(let's call ituseWorker.ts) have a configurable member that creates the worker. Basically,useWorker.tsexports a function calledsetWorkerDefinitionwhich looks something like:So that when something needs to create a worker it calls a method, call it
useWorker, that can useModuleWorkerDefinition. Something like:And lastly the new Worker call is abstracted out into a separate module, call it
defineWorker.ts:This means that
useWorker.tsdoesn't have to import the definite of a worker (which, in my case, imports some other things that were causing the circular dependency since some of those things ultimately importeduseWorker.ts). So then the last step was to get something to import defineWorker.ts so that it would register itself.In Vue this was pretty easy. In the
main.tsfor the app I just added aimport '@/defineWorker.ts';which took care of everything (since nothing importsmain.tsin my app and it will definitely always be called). The trouble is now I have a need to nest workers and I think that the only solution I can come to is to have two different "worker entry files" so that they shouldn't end up importing each other, but that still feels super brittle to me. Is there actually any hope of a real solution to this? Because at the end of the day it works fine in dev mode add just fails when it is being bundled, which tells me that there isn't actually a circular dependency to be concerned about.john-landgrave commentedon Nov 2, 2022
In talking through this with one of my teammates I think it makes sense why this is happening. Can someone confirm that this is how the bundler is working and that this logic makes sense? It seems to us that this is about the way that the bundler should be working:
I understand that there is a lot more to the process here, but as a whiteboard explanation of the process, I think that this is pretty close to what it seems to be doing? If that is the case, then assuming that there is some process/memory isolation in step 3 it would make sense that the circular loop would case the cycle to repeat over and over until you run out of memory. However, it seems like a reasonable solution to essentially create a dictionary where the keys are the import paths and the values are the files that will ultimately be created so that you can effectively reuse the output of the sub-process spawned in step 3 at any import, even if that import is inside of the worker itself, right? Because in the end this is going to show up in the bundled, transpiled, minified code as
new Worker('/some-worker.8675309.js'), right?Is this something that it would even be possible to write a Vite/Rollup plugin for, or is this just too core to the way that those tools work?
AceBear commentedon Nov 6, 2022
I had the same issue, and have found a workaround after attempting for several days. Hope this can help someone.
The key idea is forcing the vite bypassing
new Worker/SharedWorker(...)The
scriptForWorkeris a true variable, so the vite have no idea about how to process it, and will just keep it as a simple string. And then, let rollup build themyWorker.jsfor us.vite.config, let rollup build 'myWorker.js'vite.config, let vite generatemanifest.jsonnew Worker(...)npm run build # or npm run devdeluksic commentedon Feb 9, 2023
We had the exact same case (worker -> importing file -> importing same worker). However, instead of hanging, we got:
2 remaining items
jamsinclair commentedon Nov 8, 2023
I believe for a while the problem was masked by the nested workers regression (#13367). You can see this in other developer outputs above. The error would look like:
That issue was fixed in #14685 and released in v5.0.0-beta.11. The original reported issue is now present for nested workers and re-occuring from v5.0.0-beta.11.
After the next major release I think there will be an uptick in people reporting this hanging build issue as circular imports is a common pattern when working with nested workers (pun unintended) and often added automatically by dev tooling.
kleisauke commentedon Nov 8, 2023
This issue is still present in v5.0.0-beta.11. As mentioned in #14499 (comment), it can be circumvented by doing:
Details
Note that for Emscripten-generated code this would mean that the
locateFilehandler on the incoming module would have to be overridden to provide support for nested workers.jamsinclair commentedon Nov 8, 2023
I'd like to second @lgarron's idea for not separately bundling module workers. Seems like it would simplify many things. No need to worry about nested workers, parallelized builds, circular-ish dependencies and separate worker plugins. Plus reduced code duplication as modules can be shared between main entry points and module workers.
Are there any obvious or hidden pitfalls that would make this unappealing? @patak-dev @sapphi-red
Some smaller ones that I can think of are:
jamsinclair commentedon Dec 4, 2023
I've attempted to create an experimental plugin that would make Vite chunk module workers instead of bundling. It seems to work for my use case and solves the circular dependency issue (Gist of plugin source).
There's a few caveats that showed up:
new Worker(new URL('path', import.meta.url), type: { 'module' })There's likely other things that could break because the plugin simply tricks Vite into thinking the worker is a dynamic import of an ES module.
simonbuehler commentedon Dec 6, 2023
for me it worked for opencv.js wasm workers with the config from #7015 (comment) , thanks a lot!
CodeF53 commentedon Dec 8, 2023
Fixing this may solve nuxt/nuxt#22966
wcdeich4 commentedon Dec 26, 2023
I'm having a similar problem. Simple web workers are fine, but any code that imports classes & instantiates a new object inside a web worker always fails.
lgarron commentedon Mar 6, 2024
While I appreciate a partial fix in #16103 , I'd like to note that that it does far from solving the issue in general.
Trying to run
npx vite buildusing a build of eef9da1 on my repro from #14499 still fails the same way, unfortunately.#16103 states that:
I appreciate that it might not be possible to fix the current situation super easily, but it's not a matter of popular conventions. Some of us don't have a choice about the recursive dynamic imports in our code, unless we want our code to fail in other bundlers. 😢
Would it be possible to reopen one of these issues to keep track of the general problem?
npx vite buildbreaks module worker instantiation #14499Thanks,
»Lucas
sapphi-red commentedon Mar 7, 2024
@lgarron
I do think it solves most cases. I actually tested with all the repros I found and all of them worked (without throwing errors on build) as I stated in the PR. Your repro does not match the "complex case" condition.
By using the main branch (eef9da1) Vite and setting
worker.format: 'es', the build of your repro (#14499) succeeds and the preview is working.If it doesn't work on your computer, there's probably something wrong with your self-built Vite. If not, maybe there's a bug that doesn't happen on my computer?
lgarron commentedon Mar 9, 2024
That's reassuring to hear!
I tried it again, and I still can't get it to work — do you have more details on how to test?
This is what I'm doing:
Regardless of what I try to put in
vite.config.js, I now get:lgarron commentedon Mar 9, 2024
Aha! I forgot that the
vite.config.jsfile needs to be in thesrcfolder, not the project root! It works with:🤩🤩🤩
This is fantastic to see, but unfortunately it does mean people using our library will still get a confusing error out of the box.
Given that ESM is the default output for the main bundles, would it be possible to default the workers to ESM as well? I would find that much more intuitive, and it could allow significant code deduplication for some use cases.
sapphi-red commentedon Mar 10, 2024
We won't be able to do that for now. ESM workers are not supported by browsers we specify as the default value of
build.target.wcdeich4 commentedon Mar 11, 2024
what about typescript?