How to differentiate between Svelte dev mode and build mode?

12.7k views Asked by At

The dev mode using npm run dev, the release mode using npm build

How could i know that it's currently built on dev mode or not in the code, for example:

<script>
    import {onMount} from 'svelte';

    onMount(function(){
        if(DEVMODE) { // --> what's the correct one?
            console.log('this is x.svelte');
        }
    })
</script>
 
5

There are 5 answers

4
dagalti On BEST ANSWER

Not sure about the correct method. I share what I did on my project.

  1. in rollup.config.js
    import replace from "@rollup/plugin-replace";
    const production = !process.env.ROLLUP_WATCH;
    
  2. inside plugins:[ ] block add this
    replace({
        isProduction: production,
     }),
    
    rollup.config.js will look like this:
    plugins: [
      replace({
        isProduction: production,
      }),
      svelte({
        // options
      }),
    ]
    
  3. Then use isProduction inside components.
    if (!isProduction){ console.log('Developement Mode'); }
    
0
jedik On

If you are using Svelte with Vite, you may use:

import.meta.env.DEV - true in development environment.

import.meta.env.PROD - true in production environment.

import.meta.env.MODE - name of the mode, if you need more control.

See Vite docs on Env variables

0
Matheus Toniolli On

I solved this problem by checking the hostname the application is running on. You can also use other forms like, port or even msm a localStore browser variable.

Note that I check if the application is running on the client side before using the 'window'

const isProduction = (): boolean => {
  // Check if is client side
  if (typeof window !== 'undefined' && window.document !== undefined) {
    // check production hostname
    if (window?.location.hostname !== undefined && 
        window.location.hostname === 'YOUR_PRODUCTION_HOSTNAME') {
      return true
    } else {
      return false
    }
  } else {
    return false
  }
}
6
Samuel On

If you are using sveltekit:

import { dev } from '$app/environment';

if (dev) {
    //do in dev mode
}
3
Elron On

When using Svelte (not svelte-kit), this worked for me inside svelte components:

<script>
    let isProduction = import.meta.env.MODE === 'production';

    if (!isProduction) {
       console.log("Developement Mode");
    } else {
       console.log("Production Mode");
    }
</script>

Thanks timdeschryver for the reference