With Svelte : How to put component style in a separated file but still scoped to this component
Asked Answered
S

2

7

I'm working on a table component which one will be usable (included in a library when it will work correctly)in any of my projects. As there is a lot of css rules related to this component I would like to put the style outside of the component svelte file. What I did is writing a separate css file which I import in the component svelte file by :

import './table.css'; 

But in such a case I can see my rules in the built bundle.css file but these are not scoped to my component. So I'm wondering if there is way of doing it as I would like or not....

Stein answered 29/12, 2021 at 16:35 Comment(0)
C
7

yes, when svelte-preprocess is set up, you can use <style src="./table.css"></style> in the .svelte file https://github.com/sveltejs/svelte-preprocess#external-files

Cammiecammy answered 21/2, 2022 at 17:33 Comment(1)
Please don't provide such external linksTankoos
C
1

To enable preprocessing of external .css files into your svelte components, add a reference to svelte-preprocess in your svelte.config.js, like this:

import preprocess from 'svelte-preprocess'
    
export default {
    preprocess: preprocess(),
}

Then in your component.svelte, do:

<script lang="ts">
  let count: number = 0
  const increment = () => {
    count += 10;
  }
</script>

<button on:click={increment}>
  count is: {count}
</button>

<style src="./counter.css"></style>

Where ./counter.css is the file you want to import to your component.

Copalite answered 26/2, 2023 at 23:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.