This is a preprocessor for svelte that allows you to conditionally compile code based on the value of a variable.
npm install --save-dev svelte-preprocessor-ifdef
// svelte.config.js
import ifdefPreprocessor, { IFDEF_DEFAULT_REGEX } from 'svelte-preprocessor-ifdef';
const config = {
preprocess: ifdefPreprocessor({
regex: IFDEF_DEFAULT_REGEX, /* (optional) */
values: ..., /* (default: process.env) */
}),
};
<!-- App.svelte -->
<script>
/* #ifdef DEBUG */
const DEBUG = true;
/* #else */
const DEBUG = false;
/* #endif */
</script>
{#if DEBUG}
<p>Debug mode</p>
{/if}
DEBUG=true npm run build
Output:
<!-- App.svelte -->
<script>
const DEBUG = true;
</script>
{#if DEBUG}
<p>Debug mode</p>
{/if}
<!-- App.svelte -->
<script>
/* #ifdef (SOME_VAR === 'foo' && SOME_OTHER_VAR='bar') */
import "side-effect-package";
/* #endif */
</script>
<p>Some content</p>
SOME_VAR=foo npm run build
Output:
<!-- App.svelte -->
<script>
import "side-effect-package";
</script>
<p>Some content</p>