Search code examples
sveltesveltekit

How can I have seperate functionality in development and release builds in sveltekit?


What i am trying to do is have a some debug tools that are present in development builds, eg. yarn run dev but are not accessible in release builds, eg. yarn run build

thanks.

I have done some googling, but i couldn't find anything. Sorry if I phrased my problem weirdly.


Solution

  • You can e.g. either define a replacement constant via Vite's define or use static environment variables.

    Via define:

    // vite.config.js
    export default defineConfig((cfg) => ({
        define: {
            VITE_DEV: cfg.mode === 'development',
        },
        plugins: [sveltekit()]
    }));
    
    // src/app.d.ts
    declare global {
        // To prevent type errors when using TS
        declare const VITE_DEV: boolean;
    
        namespace App {
            ...
        }
    }
    

    Then on a page:

    <script lang="ts">
        import DebugTools from './debug-tools.svelte';
    </script>
    
    <!-- [regular content] -->
    
    {#if VITE_DEV}
        DEBUG MODE
        <DebugTools />
    {/if}
    

    Via environment variables:

    <script lang="ts">
        import DebugTools from './debug-tools.svelte';
        import { PUBLIC_DEBUG_MODE } from '$env/static/public';
    </script>
    
    <!-- [regular content] -->
    
    {#if PUBLIC_DEBUG_MODE == 'true'}
        DEBUG MODE
        <DebugTools />
    {/if}
    

    How the PUBLIC_DEBUG_MODE is set depends on the operating system.
    You could e.g. set the variable directly in the package.json scripts section.
    Note that if the variable is not defined, the build will fail.


    Since in both cases the code is statically processed during the build process, the debug code (including the debug component import) can be automatically eliminated via tree shaking.

    (For Svelte 5 there currently is a bug in that regard.)