Reputation: 1309
So I have a setup where I want to allow custom components to be created and referenced via an API fetch call made by my react client site.
I know using dynamic imports and React.lazy these can be loaded dynamically instead of with the rest of the bundle.
https://reactjs.org/docs/code-splitting.html
And I know ES6 imports support importing from urls
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
So is it possible to load a component from a url? I tried and got the error:
OtherComponent.js hosted at url
function OtherComponent() {
return (
<div>Other component</div>
)
}
export default OtherComponent;
A snippet of my code
const url = '/url/to/OtherComponent.js'; // this is found via a fetch request, so not known beforehand
const OtherComponent = React.lazy(() => import(url));
...
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent {...props} />
</Suspense>
Uncaught SyntaxError: Unexpected token '<'
I'm assuming because it's loading in a normal javascript file and not whatever modified chunk file the webpack build process creates.
Is what I'm trying to do impossible? Would the only way to be to rebuild with every new component added/modified?
Upvotes: 4
Views: 1592
Reputation: 17
The problem is that the URL you have ('/url/to/OtherComponent.js') is dynamic and could be fetched from an API. React.lazy can't directly handle dynamic URLs in this manner because it needs to resolve the module ahead of time.
Here's how you can handle this:
Ensure that the URL is known before passing to React.lazy: You can wrap the logic in a state or use a hook to fetch the URL using Fetch API, and only call React.lazy after the URL is known.
Use dynamic imports once the URL is available
React.lazy only accepts a dynamic import function, which works with static module paths.
Upvotes: 1
Reputation: 104
You can have a look at this discussion for the same issues you encoutering: https://github.com/facebook/react/issues/16132
Technically, the webpack in React is not supporting this part of your code:
import(url)
But there are some frameworks or other library could support it:
https://v8.dev/features/dynamic-import
https://loadable-components.com/docs/getting-started/
Or you can use webpack require-context like this: https://webpack.js.org/guides/dependency-management/#requirecontext
Upvotes: -1