How to run script before building in Sveltekit?

276 Views Asked by At

I need to run a script in my static sveltekit application that makes a request to a remote API before the application build happens, I have a question, in which part of the project should I do this? My script is supposed to retrieve images from the server and save them to the static folder for later use in the project.

2

There are 2 best solutions below

2
On

sveltekit's build functionalities are built on top of vite. You might be able to write a vite plugin to accomplish what you're trying to do. For example, in your vite.config.js file:

import { vitePreprocess } from '@sveltejs/kit/vite';

export default {
  preprocess: [vitePreprocess()],
  plugins: [getImages()],
};

function getImages() {
    return {
        buildStart: () => {
             // your logic here for fetching the images and saving them to disk
        }
    }
}

more information here about build hooks in vite

0
On

The default vite.config.js file looks something like this

import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';

export default defineConfig({
    plugins: [sveltekit()]
});

You can add your own plugin to get the images as follows. You can use fetch and fs module to fetch and save images as usual.

import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';

const getImages = () => {         // could be synchronous or async
    return {
        buildStart: () => {         // could be sync or async
            // your code using fetch and fs 
        }
    }
}

export default defineConfig({
    plugins: [sveltekit()]
});

Vite Plugin Api provides comprehensive documentation about writing your plugin. And if the order of execution matters you can find out about ordering here. I have used the "buildStart" hook as @boreddad420 has mentioned, as it suits this application. You can find out more about Vite hooks here.


Even though the order of execution could be configured using the order parameter it sometimes doesn't play nice. For example I had to dynamically generate app.html before any build step from the svelte plugin. And this could not be accomplished using the order parameter so this was a simple hack I used to run my code before anything from svelte plugin executes.

Create a wrapper function that accepts the plugin function as an argument and return the result of the plugin function.

import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';


const wrapper = async (wrapped) => {
    // your code
    
    return wrapped();
}

export default defineConfig({
    plugins: [wrapper(sveltekit)]
});

Although I don't recommend this over writing your code as a plugin, This guarantees that your code runs before the svelte plugin.

Hope this helps.