javascripttypescriptvitesveltesveltekit

Can't import image in build in Svelte


I have a SvelteKkit app, it has an upload image function that saves the image in $lib/images directory.

 const carDirectory = path.join('src', 'lib', 'images');

    // Ensure the car's directory exists
    if (!fs.existsSync(carDirectory)) {
      fs.mkdirSync(carDirectory, { recursive: true });
    }

    // Function to save the file with a generated name
    const saveFile = async (file: File, baseName: string) => {
      const extension = path.extname(file.name); // Extract the file extension from the original name
      const fileName = `${registration}${extension}`; // Construct the new file name without timestamp
      const filePath = path.join(carDirectory, fileName); // Construct the full file path

      // Convert the file to an array buffer and then to a buffer
      const arrayBuffer = await file.arrayBuffer();
      const buffer = new Uint8Array(arrayBuffer); // Use Uint8Array for compatibility

      // Write the buffer to the file system
      fs.writeFileSync(filePath, buffer);
    };

and it imports the image in the card.svelte component

 onMount( async () => {
    image = (await import(`$lib/images/${registration}.jpg`)).default;
  });

The upload function works in the development and build version, but the import function does not work in the build version.

I tried the Svelte's own dynamic import using Vite build tool but it only works in the development version.


Solution

  • Imports like this are a Vite feature. Vite will find all files matching the pattern and emit them as static assets. SvelteKit also will not serve anything that was not there at build time.

    Would recommend creating a custom endpoint (+server.js/ts) for retrieving uploaded images or depending on adapter being used use a different mechanism, e.g. for a custom Node server add a respective middleware.

    (For serverless platform adapters, uploading files and saving them locally is generally not a good idea in the first place since all deployed files are ephemeral. Everything can be reset when nodes are spun up and down depending on demand.)