Dynamic Import Exception Handling
Asked Answered
F

1

7

I use ES6 dynamic import to accomplish code splitting in my React App. However, I'd like to auth protect the app, and noticed that when import() goes out to fetch JS chunks or CSS, it gets a 401, as expected. However, when I catch the exception via:

import("Component1").then( 
    module => this.setState({ module }) ).catch( 
    err => console.log(err) 
);

The error that gets returned via "err" does not contain the HTTP response and status code (401). Is there anyway to trap this? I assume import() has to do fetch() under the covers, which will have access to it.

Felixfeliza answered 18/10, 2018 at 21:56 Comment(0)
F
2

So, I want to follow up with some things I found out about Dynamic Imports. Looking deep into webpack's source code, I found that it uses a <script> tag to fetch chunks, and because of this the script's onerror callback doesn't provide status codes or responses.

This helpful response here helped me understand why much better and how one would go about implementing chunks as xhr requests instead of script loading (spoiler alert: you'll need to implement a new webpack plugin): https://mcmap.net/q/1627649/-is-it-possible-to-let-webpacks-system-import-use-ajax-for-progress-events

Felixfeliza answered 19/10, 2018 at 13:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.