-
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
TypeError: Failed to fetch dynamically imported module #11804
Comments
This is not something specific to Vite and happens with Webpack, too. https://mitchgavan.com/code-splitting-react-safely/ I don't have any idea to solve this on a bundler side. |
We are experiencing the same issues with a vite+vue SSR application. |
Thanks @sapphi-red, is it Vite or Rollup generating these hashes (assuming that's what they are) on the filenames? I wonder if there's a way to suppress that behaviour and if it's required for cache busting whether there's any alternative approaches. |
@sapphi-red both generate hashes when running the build. If your product it's a SPA you can try to use a service worker together with an interceptor (if you use Axios) to manage that. I did it on Vue 2 where it's basically stores on the localStorage a version of the app and then compares if the one that you access it's the same or not and if not it triggers a reload of the browser in order to get the updated version |
@victorlmneves could you provide a bit of a fuller explanation/ code snippets maybe of tha so I understand the concepts a bit more? I'd be quite interested in exploring what that might look like. |
@IPWright83 And here is an example that I did some years ago
And another one using Axios interceptors
|
@IPWright83 import { defineConfig } from 'vite'
export default defineConfig({
build: {
rollupOptions: {
entryFileNames: '[name].js',
chunkFileNames: '[name].js'
}
}
}) But yes this is recommended for cache busting. I don't know any alternatives other than the ones described in the articles I linked above. |
@IPWright83 by the way, have you tried to access directly the file that is displayed on the console that wasn't possible to import? I'm asking because on our project we get those errors randomly but when we access them directly the file exist |
I have @victorlmneves. Is there any way to adopt an approach more like this #5825 @sapphi-red? Anything after the queryString can still cache-bust, but as the file name is constant you'll get the new payload. I think that example is a little primitive (I think JS needs transforming too). Could you see any issues with this approach? |
I guess it's possbile by using a plugin. For example, // foo.js
export const foo = 'foo'
export const bar = 'bar'
// a file depends on foo.js
import('./foo.js').then(mod => {
if (mod.bar.startsWith('b')) {
console.log(mod.foo)
}
}) second version deployed // foo.js
export const foo = 'foo'
// a file depends on foo.js
import('./foo.js').then(mod => {
console.log(mod.foo)
}) |
@IPWright83
|
@victorlmneves yeah, that works for |
Any updates on this? The vue router hack could work for some imports, but we have dynamic imports outside of the router, which i don't think the hack would be able to cover. Besides, forcing a reload because an error occurred doesn't seem like the best UX, so wondering if there's a solution/workaround that is more subtle and "behind the scenes" 🤔 |
While I understand that we should try to solve this problem ourselves, it seems like this must be quite a fundamental problem that developers will have when creating apps with vite? Especially when continuous deployment comes into the mix, because the files update very often and trigger lots of errors. For now I am back to "nightly deployments" to try and minimize disruption 😬. It would be great if there was a standard solution somewhere in the docs. Preferably one without making the users manually "opt-in" to a page reload. Even nicer would be if vite could somehow handle it for us so we don't have to do anything. Eg catch the error and refresh the files without a hard reload of the page. That would greatly improve the DX 🙂. Thanks for all the great work. Vite is awesome. |
@yakobe in my case, it's not about outdated chunks. I'm getting this with existing files that is even worst to figure out the problem and try to fix it, especially because the only way I'm able to reproduce the issue it's shutting down the node server (I have SSR app) :/ |
This reverts commit b1fc7bf. Workaround for vitejs/vite#11804
For what it's worth, an ad-blocker was the root of this issue for me. Disabling it resolved my issue. |
A lot of Cypress users run into this: cypress-io/cypress#25913 I don't think I can fix it on the Cypress end. I can spend time (several days of development resources) to patch Vite if needed, but it looks like the cause isn't entirely clear. Some observations:
Any tips -- maybe from someone more familiar with Vite - on debugging this? I will inspect Cypress more first and keep the limitations in mind. |
We are just hitting this now too, but it's not just when the user has a browser tab open. It can also happen much later, if the user returns to our app after we have deployed. We're trying to work out if it's caused by the
I'm still confirming this but I wondered if it matches anyone else's experience/setup? |
Happened to me after upgrading from vite 4.0.1 to 4.1.4 |
@benadamstyles I had the same issue. I removed the hashing option in the config like another user mentioned. |
Not sure if related but I'm getting the same error when using storybook with a react component that imports a module from an |
same |
I reproduced this in CI only, you can follow my progress as I debug it in Cypress: cypress-io/cypress#25913 (comment) I suspect the same core issue. I think it's a race condition or resources related issue. |
I think there are possibly two separate issues being described by different users/teams in this thread:
For people experiencing issue 1., the solution is to organise your deployments so that old versions aren't deleted immediately. Doing a deployment of new app code doesn't mean that all users running your app in their browser will update immediately (unless you force it somehow). For those users who still have an older version running in their browser (lets say For users that load the app after a deployment, If you keep a manifest of each deployment, and your instrumentation/logging includes the "version" of the app users are using, you should be able to figure out how long old versions are still used. My team has seen users still operating in the same tab they loaded a month ago without updating, so we keep all our built assets deployed for a long time. If you want to force users to reload when a new version is deployed, that's a whole piece of engineering in itself. |
According to quite a bit of research in cypress-io/cypress#25913 at least one class of error is related to CI on GH Actions specifically - not sure if this helps anyone, but worth noting in case it does. |
Is it also a way to add |
@SecretCastle No, see this example: Let's say, to reduce the initial bundle size, you choose to bundle by page. Let's walk through what that means:
Note: For ease of understanding I ignored that Vite does not produce chunks in the form of In essence, the index.js contains a map of lazy imports('some-file.js') statements to files on you server (example.com/chunk-xxxx.js). That map becomes stale in redeployments because the chunk filenames for components differ. That's also why choosing explicit chunk filenames can relieve the problem, as you can choose chunk filenames that will remain correct between deployments. Caches won't help when redeployments change your filename -- but they do make it worse, as they prolong the span in which errors occur if you do not invalidate the cache. The full solution to this problem is to keep past deployment chunk-xxxx.js files around. Because they are shorted sha256 hashes, it serves like a content-addressable filesystem and thus new files only overwrite old deployment files if the content of the files are the same, in which case we do not care. Hope that helps everyone wrap their head around the problem. Have a nice day! |
@liamvdv thanks. Your explanation is excellent. I understand that in this case, the essence is that the user did not refresh the page and the request was still for the historical bundle. I don't know if my understanding is correct. |
I saw this error when vitest started to fail on some of the tests, I cleaned up vite cache ( |
I am using a aws infrastructure with vue3, vue router, and vite. The workaround from vite (https://vitejs.dev/guide/build#load-error-handling) does not solve the problem. Any progress / help? Thx! |
This happens on Angular 17 with SSR when new deployment happens. Builder |
https://vitejs.dev/guide/build#load-error-handling I don't use Angular but this seems to be the solution from what ppl above have noted. This would go in the Angular file equivalent to main.tsx/index.tsx file (for React) |
The errors is actually kinda misleading. If you open the files that failed to be imported, some may contain "Cannot find static asset". {"url":"/_nuxt/9Ima4rhO.js","statusCode":404,"statusMessage":"Cannot find static asset /_nuxt/9Ima4rhO.js","message":"Cannot find static asset /_nuxt/9Ima4rhO.js","stack":""} In my case, adding "routeRules" to ''nuxt.config.ts'' resolves the issue.routeRules: { |
For me it was the server config. It was not recognizing .mjs extentions as javascript. .mjs is a new javascript extention that represents modules. So I updated my .htaccess to include this: |
We had a similar issue. It was caused by a workbox precache manifest and the cache eviction functionality of google chrome. In our app the service worker was caching opague responses, leading to exceeded storage quota. This lead to the eviction of the dynamic module resulting in the error above. If you are using service workers or had been using service workers:
hope this helps! |
Quick update guys, for Angular with es-build, the issue was forgotten `"outputHashing": "all" in the angular.json (or project.json) for the production build. Without that the main.js was not with hashing in the output build and then it was cached when new deploy was done and it was looking in chunk files with the old hashings. |
A bad autocomplete in VSCode put this in one of my files. |
Was running into this too, and found that Vite now emits a https://vitejs.dev/guide/build#load-error-handling But it also seems like this issue has to do with your hosting service. In our case, we're using Heroku which seemingly isn't keeping older versions around, and perhaps there's a way to configure this to keep them for some time as an alternative workaround. |
🚀 |
so @mberneti has fix for this issue This utility function retryDynamicImport enhances React’s lazy loading mechanism by adding retry logic with a versioned query parameter. It retries importing a component multiple times in case of failure, which can be useful for bypassing browser cache or dealing with intermittent network issues. https://gist.github.com/mberneti/28769391cf27f7580a55dedab342c63a |
Did you find the solution? The same problem randomly (on page refresh) after deploying.
or
or both. UPD: it was a deploy problem in my case. |
@mityaua can you explain your solution? |
Sure, but it seems not relevant to most of the cases that are written here. We had two docker containers, that worked together. After deployment one of the containers used to stop the other one and we were getting the previous app version. From this, it can be concluded that it was a problem with the cache update, cuz all worked perfectly in the local environment. We "kill" the unnecessary container and now the problem is gone. |
Having the same issue |
I've also been struggling with the same issue, and I've done some research. We updated our production app from Webpack to Vite and added dynamic imports for our pages (80+). In local development, everything worked fine, but when we deployed to production, our users started encountering errors like:
We noticed this issue occurs whenever we send updates to our server after merging a pull request into the To temporarily address the issue, we used a solution from the Vite documentation that reloads the page when a preload error occurs: window.addEventListener('vite:preloadError', (event) => {
window.location.reload();
}); This helped stop the alerts from our users, but we weren’t satisfied with this workaround. To investigate further, I created a test React app with Vite and a basic
As the next step, I’m planning to experiment with cache settings on my server to see if that resolves the issue. |
We had this issue on production only. We have 5 web servers which all generated a different hash key for files using the vite build command, even though the files content was the same and deployed at same time. |
Describe the bug
Since switching to Vite we noticed a new production issue, where sometimes users are encountering an error if we deploy while they have an active session:
I believe this is because if any code is modified in an area that Vite would turn into a dynamic module, then the file hash changes, however when they try to visit an area that would trigger the dynamic load, those files no longer exist so they hit the error message above.
Quoting from https://stackoverflow.com/a/74057337/21061
What I expect to happen, is not to encounter any errors if the users session remains active during a deployment.
I have been unable to come up with a good workaround (specifically for me using React ErrorBoundary is the best I can do so far with a re-direct similar to https://stackoverflow.com/a/74861436/21061 which is a mitigation and provides quite a poor user experience flashing an error message).
Reproduction
https://github.com/IPWright83/vite-dynamic-import
Steps to reproduce
The above repository has been set up to mimick a production deployment as obviously that is a much more complicated set-up. It leverages
React.lazy
to force a dynamic module and uses asetTimeout
to provide a delay with which to simulate a user navigation to a page requiring a module. In a real production scenario I don't believeReact.lazy
is required.Clone the above repository
npm install
npm run build
open a 2nd terminal
Terminal 1 npx serve dist (starts a web server)
Browser open the URL (usually localhost:3000)
Text Editor modify src/Foo.jsx changing the string "Foo" to something else (within 30s of launching the page - increase the setTimeout in App.jsx if this is not long enough)
Terminal 2 npm run build
Wait... 30s after loading the page you should see a blank page render with errors in the browser console:
If you were to reload the page, you can see that
Foo-b53985a6.js
has been renamed toFoo-535d5a10.js
(or similar new hash)System Info
The text was updated successfully, but these errors were encountered: