2

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?

  • 1
    Your `OtherComponent.js` file needs to be transpiled because it contains JSX which browsers do not understand natively. After that, it should work. – Valentin Feb 06 '23 at 21:22
  • Yeah, that's what I figured. Is there anyway to transpile after the rest of the app has been built and bundled? As in if there's some react function that does it – Programmer Unextraordinair Feb 07 '23 at 04:41
  • Unless you load a transformer like `babel` or `typescript` in the browser, no. And if you do, it's going to be quite inefficient because these transformers are heavy. If your `OtherComponent.js` is part of your project, you should let your bundler emit a chunk for it (works out of the box with Vite.js among others). – Valentin Feb 07 '23 at 07:57

0 Answers0