lukejacksonn/csz

Fetch should consider document.baseURI

MeloJR opened this issue · 6 comments

Hi, I am using this library in a project that deploy itself in a path under the root domain. All my dependecies work well because I use a <base href=/PATH/ > in my index.html but the library is using fetch with absolute paths so it ignores the base. I have solved my problem using a helper function that prepend the preffix before calling css but I think that maybe it will be useful for other users (and it is easy to add, I think).

This sounds doable.. I haven't used <base href=/PATH/ > in a while. Is there a way to pick this up in Javascript an if so is it just a case of prefixing the urls with this variable?

You can use document.baseURI for get the url with protocol and domain or new URL(document.baseURI).pathname in order to get the path only. You should take care if the baseURI finished in / to avoid having // in the URL.

Awesome, do you fancy making a PR for this?

I was thinking about it and I think that it is better to add support for relative paths (path that starts with ./) so fetch uses document.baseURI automatically.

Basically from this

const isExternalStyleSheet = key => /^(\/|https?:\/\/)/.test(key.trim());

to

const isExternalStyleSheet = key => /^(\/|\.\/|https?:\/\/)/.test(key.trim());

What do you think? I think it is a better solution.

This certainly sounds like a better option! A much less involved change.. have you tested it and does it work for your use case and not break others?

(sincere apologies for no tests)

I test it in my project and it works well but I don't test it in other cases. I think it should not break anything unless you use a class name that starts with / something like ./WHATEVER (I think that it is not normal but a valid css class name). Maybe the regex has to test about the file extensión to avoid conflicts with some rare class names. The problem with this last approach is that if you serve files behind a server without a file extension in the url (like https://MY_URL/styles/App) it will failed. The problem with the rare class names can be avoid by the user changing

css`
  ./NAME { ...properties }
`

to

css`
  & {
    ./NAME { ...properties }
  }
`

What do you think?