Accudio / async-alpine

Async Alpine brings advanced code splitting and lazy-loading to Alpine.js components!
https://async-alpine.dev
Apache License 2.0
152 stars 12 forks source link

CORS Error #21

Closed StefanVesper closed 1 year ago

StefanVesper commented 1 year ago

Hey there!

First of all thanks for this repo! I tried it out but I always run into the same issue :

async-alpine.script.js:1 Uncaught (in promise) TypeError: Failed to resolve module specifier 'myComponent.js'. The base URL is about:blank because import() is called from a CORS-cross-origin script.

The myComponent.js file is in a public folder and uses your example code from the readme.

Is this happening because I am loading your script via cdn?

I am using the cdn-link from the readme.

And, btw, will there be a cdn link for the new beta?

Accudio commented 1 year ago

Hi!

I'll start with saying there won't be a CDN link for the 0.4 beta. If you want to test you are welcome to take /dist/async-alpine.script.js from the 0.4-rebuild branch and host it anywhere you'd like. You can also get a CDN URL for files on GitHub branches with rawgit.net, enter the URL to the async-alpine.script.js file and it'll create a CDN URL.

I plan to release it fairly soon however, at that point I'll update the CDN link in the Readme.

I believe the issue you're having is due to the import happening relative to the origin that async-alpine is loaded from. So when /mycomponent.js is used when the script is loaded from a CDN it looks for that file on the CDN.

A temporary workaround for this would be using the full absolute URL for the component file within ax-load-src, so if your site was hosted on https://example.com then use https://example.com/mycomponent.js.

The solution would probably be for the 'script' (non-module) version of Async Alpine to check if it's been loaded from a CDN and if so add the local URL to any relative component URLs. I'll see if I can put that in for the 0.4 release, otherwise it will be 0.5.

Accudio commented 1 year ago

@StefanVesper I've added a fix in the latest commit of the 0.4-rebuild branch which should fix your issue, and will be out in version 0.4. If you want to test it then please do, you can use Rawgit for the CDN URL.

When a relative URL was being used in ax-load-src and Async Alpine was being loaded from a different origin it was resolving against that one instead of the document as was expected. I've tweaked it so that whenever a relative URL is used it is converted to an absolute URL with the base of the document origin which I think is more expected behaviour.

StefanVesper commented 1 year ago

@Accudio That´s great news! I was offline for some days.. I will today update our implementation to 0.4 and see whats happening :-) It is great to be able to dynamically load components now! Will keep you informed! Thanks! Stefan