skip to Main Content

I made a component in SvelteKit that will have different styles based on the data provided.
Part of the conditional styles are some background images that should be one of either two:

The style tag looks like this:

{#if true}
  <style>
  ...
  .branch.ezzeddin {
      background-image: url('$lib/assets/ezzeddin-logo-minified.png');
  }
  ...
  </style>
{/if}

With this {#if} block I get the following error that the image doesn’t exist, because somehow the compiler takes in the image url string as is and doesn’t link to the actual image:

Error: Not found: /$lib/assets/ezzeddin-logo-minified.png
    at resolve (C:/Users/hosam/Desktop/Work/Dev/recruitement-interface/node_modules/@sveltejs/kit/src/runtime/server/respond.js:430:13)
    at resolve (C:/Users/hosam/Desktop/Work/Dev/recruitement-interface/node_modules/@sveltejs/kit/src/runtime/server/respond.js:277:5)
    at Object.#options.hooks.handle (C:/Users/hosam/Desktop/Work/Dev/recruitement-interface/node_modules/@sveltejs/kit/src/runtime/server/index.js:49:56)
    at Module.respond (C:/Users/hosam/Desktop/Work/Dev/recruitement-interface/node_modules/@sveltejs/kit/src/runtime/server/respond.js:274:40)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

When I remove the {#if} block everything works fine, but some styles get applied that I don’t want to.
And I don’t want to separate the logic into two components because otherwise I’ll end up with so many duplicate code.

2

Answers


  1. EDITED:
    use H.B.’s Answer‘s method in stead:

    <!-- div with conditional styling -->
    <div class="branch" class:ezzedin={true} />
    
    <style>
      ...
      .branch.ezzeddin {
        background-image: url('$lib/assets/ezzeddin-logo-minified.png');
      }
      ...
    </style>
    

    If for whatever reason you would still like to keep the import in the script tag you may do the following:

    <script>
      import logo from "$lib/assets/ezzeddin-logo-minified.png";
    </script>
    
    <!-- div with conditional styling -->
    <div class="branch ezzedin" style="--logo-url:'{logo}'" />
    
    <style>
      ...
      .branch.ezzeddin {
        background-image: url(var(--logo-url));
      }
      ...
    </style>
    
    Login or Signup to reply.
  2. You should not try this. This probably also breaks scoping and style extraction because the style would not longer be treated as the component style tag.

    If you want styles to apply conditionally, just add classes conditionally, e.g. using class:name directives. With a CSS preprocessor1 you then can just nest everything inside blocks.

    1 Requires a Svelte preprocessor, like the one from the Vite plugin.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search