antfu-collective / vite-ssg

Static site generation for Vue 3 on Vite
MIT License
1.27k stars 129 forks source link

fetch gives 'ERR_INVALID_URL' #394

Open samzuercher opened 3 months ago

samzuercher commented 3 months ago

Describe the bug

I try to dynamically language-.json's located in the public-directory. If i can not find any, i try to fetch the english-one like this: const response = await fetch("/en.json");

Everything works nice with cross-env DEBUG=vite-ssg:* vite. When running vite-ssg build --mode ssg it builds for client but fails building for server with this:

TypeError: Failed to parse URL from /en.json at node:internal/deps/undici/undici:12345:11 at async SetLanguage (file:///Y:/02_d/01_repos/01_primabit/landingpage01/.vite-ssg-temp/fkde5vqeqn/main.mjs:66:22) { [cause]: TypeError: Invalid URL at new URL (node:internal/url:775:36) at new Request (node:internal/deps/undici/undici:5853:25) at fetch (node:internal/deps/undici/undici:10123:25) at Object.fetch (node:internal/deps/undici/undici:12344:10) at fetch (node:internal/process/pre_execution:336:27) at SetLanguage (file:///Y:/02_d/01_repos/01_primabit/landingpage01/.vite-ssg-temp/fkde5vqeqn/main.mjs:66:28) { code: 'ERR_INVALID_URL', input: '/en.json' } }

Several Questions:

  1. Why is vite-ssg checking URLs? Probably to determine which files to put in the output directory. But If i fetch something from some external API, it would always detect errors as the api might not be up and running??
  2. In this case, it is fetched from the public folder and should not be checked at all

Reproduction

Please see description

System Info

System:
    OS: Windows 11 10.0.22631
    CPU: (6) x64 Apple Silicon
    Memory: 6.40 GB / 19.53 GB
  Binaries:
    Node: 20.11.1 - C:\Program Files\nodejs\node.EXE
    npm: 10.2.4 - C:\Program Files\nodejs\npm.CMD
    pnpm: 8.15.4 - ~\AppData\Local\pnpm\pnpm.EXE
  Browsers:
    Chrome: 123.0.6312.86
    Edge: Chromium (123.0.2420.65)
    Internet Explorer: 11.0.22621.1

Used Package Manager

npm

Validations

samzuercher commented 3 months ago

I found a workaround:

export async function SetLanguage(lang?: ELanguages) {
  if (typeof window !== 'undefined') {
      // do stuff
      const response = await fetch("/en.json");
  }
}

Basically just not doing anything when on the server. I think others had similar questions: ~build client-only: https://github.com/antfu/vite-ssg/issues/101

I also tried:

<template>
  <ClientOnly>
  <main>
    <RouterView />
  </main>
  </ClientOnly>
</template>

But <ClientOnly> seems to have no effect and was not found..

Why client-only? I like vue to build the frontend. But then i need static files to be hosted on a file server, as the backend might be running in .NET or on Kubernetes and be connected only with API-Calls.