admin管理员组

文章数量:1402415

How can I offload ReactJS and various ReactJS components (not mine, but Bootstrap, leaflet etc.) to load from a CDN rather than be bundled with my app to keep the size of my app that I host as small as possible (bundled it's 500kb, calling scripts from CDN it's 13kb).

I did have this working by placing the ESM links to the CDN in the from section, but then on a rebuild started getting random errors where it seemed that code was being asked to run before it had finished downloading and parsing.

How can I offload ReactJS and various ReactJS components (not mine, but Bootstrap, leaflet etc.) to load from a CDN rather than be bundled with my app to keep the size of my app that I host as small as possible (bundled it's 500kb, calling scripts from CDN it's 13kb).

I did have this working by placing the ESM links to the CDN in the from section, but then on a rebuild started getting random errors where it seemed that code was being asked to run before it had finished downloading and parsing.

Share Improve this question edited Mar 23 at 16:48 Hamed Jimoh 1,3918 silver badges20 bronze badges asked Mar 23 at 11:21 Richard ConyardRichard Conyard 697 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Having gone down nearly every rabbit hole and plugin available I now have a working solution for ReactJS 19.0.0.

  • import like normal in the applications .jsx files replacing (for example): import { createRoute } from 'react-dom/client';

with

import { createRoute } from 'https://esm.sh/[email protected]/client''

Where the number is the version and create a service worker to cache off the requests as not to go over the esm.sh build limitation.

Lessons learnt do avoid others following the rabbit holes:

  • With ReactJS 19 UMD is no longer supported, most plugins I've found rely on UMD. Unless they state they use ESM stay clear.
  • esm.sh is the only CDN I have found that reliably serves ESM versions of libraries and had the libraries I needed (what jsdelivr calls react-dom/client I have still yet to find out)
  • Following the pattern of importing into the browser (like UMD), really doesn't seem to play ball when using ESM. Whereas UMD placed imports into the global context EMS doesn't (or if it doesn't I couldn't find them). On top of this Vite will remove them on the distribution build.
  • If you are referencing the modules by https then you do not need to go down the route of externals etc. with Vite.

I hope this helps anyone who comes across this in the future since with so many legacy guides around and work arounds were this couldn't be done easily in the past what is exceptionally simple has wasted 3 days of my time!

本文标签: reactjsReactVite using CDN instead of bundlingStack Overflow