Reputation: 762
A quick problem I faced while developing a web-app using SvelteKit (and by extension, Vite):
Inside the <script>
tag of my +page.svelte
file I tried defining an empty placeholder File
object the following way:
let formObject: FormCreationData = {
fileToUpload: new File([], ''),
anotherField: "",
...
};
While it should work in normal JS/TS (and Svelte if you aren't using SvelteKit), it now throws the following error:
ReferenceError: File is not defined
at +page.svelte:13:14
Why is this the case?
Upvotes: 2
Views: 1014
Reputation: 762
Since SvelteKit implements Server-Side Rendering (SSR) - The code that is on the +page.svelte
file has to run both on client browsers and the Vite server.
The File
class is only available in browsers, so it won't be able to fulfill this requirement (You might know that Node.js offers the fs
module in order to allow for file operations instead).
This means that there are two ways to possibly fix this problem:
Disable SSR using the variable ssr
in the +page.ts/js
file:
export const ssr = false;
Find a way to define the File
object at a point where the code runs on the browser (This can be done by checking the browser
variable under the $app/environment
module, or inside of one of the supported Svelte hooks, such as onMount()
).
Upvotes: 2