Is it possible for now or we should use something like CSS modules: https://www.npmjs.com/package/@modular-css/svelte
I couldn't find answer to this question / feature request. Sorry if it was really answered before 馃檮
<script>
import './Counter.css';
let count = 0;
function handleClick() {
count += 1;
}
</script>
I have opinions as the author of that package, but fundamentally what are you trying to do by importing a .css file into your .svelte file? The answer to that will help us answer your original question better.
Separate CSS from js and html. For example, I have Button.svelte component, it has a lot of variants (https://material-ui.com/components/buttons/):
Almost each with own hover effect and disabled state.
Without something like CSS modules we will have X2 file cause of styles, e.g.:
https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/Button/Button.js#L9-L182
Any sort of .css comprehension plugin for your bundler of choice will get you that functionality. Svelte doesn't really care so long as it gets back a JS object you apply in the template.
<div class="{css.bd}">...</div>
<style>
import css from "./Component.css";
</style>
You could achieve that with CSS Modules, modular-css, or anything without svelte needing to do anything special.
The @modular-css/svelte package you linked is essentially a build-time optimization step that inlines as much styling as possible at build-time instead of run-time to help svelte generate smaller components.
<link href="./Component.css" />
<div class="{css.bd}">...</div>
In that example css.bd will be replaced before svelte ever sees it so as far as the compiler knows it's just a static class and it gets you smaller/faster code. I think it's awesome (very biased though lol) but It's not required if you want to use a CSS Modules style library with svelte.
This post its old but i use this solution, vars on parent component
:root {
--primary__color: #6002ee;
}
On children components
.button {
background: var(--primary__color);
}
on sapper i put all my vars on layout file
Most helpful comment
Any sort of
.csscomprehension plugin for your bundler of choice will get you that functionality. Svelte doesn't really care so long as it gets back a JS object you apply in the template.You could achieve that with CSS Modules,
modular-css, or anything without svelte needing to do anything special.The
@modular-css/sveltepackage you linked is essentially a build-time optimization step that inlines as much styling as possible at build-time instead of run-time to help svelte generate smaller components.In that example
css.bdwill be replaced before svelte ever sees it so as far as the compiler knows it's just a static class and it gets you smaller/faster code. I think it's awesome (very biased though lol) but It's not required if you want to use a CSS Modules style library with svelte.