#Dynamic css load

7 messages · Page 1 of 1 (latest)

split thunder
#

Hi,
i have a problem with scss.
I must create a static site for my companies but i must load different scss based on route parameters, each company has your scss.
The problem is thant Astro load all scss.
Code example

---
const { company } = Astro.params;
if(company === "company1") {
  import "../styles/company1.scss":
} else {
  import "../styles/company2.scss";
}
---
... layout html load

What could be the solution?

fierce path
#

I have never tried this... But basically imports like that are always hoisted to the top of the file so that won't work how you have it there.

But we can use the import function from vite and dynamically import it. And then... Somehow get it into the dom....

---
let css
if (a) {
  css = import('./company1.scss') // .data??????
} else {
  css = import('./company2.scss')
}
---

<style set:text={css}>

Something..... Like that? Ngl I have no idea if this will work, but something like that I think would be your best bet. I'm just not 100% sure what happens when you import a scss file 🤔 I don't know if that gets transpiled before you get it in your astro component... I'm not sure...

Or maybe something like

let css
if (a) {
  css = `import './company1.scss'
} else {
  css = `import './company2.scss'
}
---

<script define:vars={{ css }}>
  import(css)
</script>
split thunder
#

Thanks for the reply, but unfortunately it doesn't work.
Both files are imported.

analog raptor
#

I'm having the same issue, is there any recommended solution now? Maybe some new feature in Astro that makes this easier?

I mean setting dynamic class names and applying CSS based on that would be an option, but this is way less maintainable then just dynamically importing the CSS file I need...

analog raptor
#

Okay, I think it's an issue with Node itself, because they dont let me import dynamic CSS; solved it by using classnames and writing the CSS with body:has(.class-name)...

wicked sorrel
#

Anyone found a good solution for this?

The best I could come up with is having one Astro component per theme. eg: FancyTheme.astro and CoolTheme.astro etc

Each component simply imports a css file:

---
import 'src/css/fancy.css'
---

And then on my BaseLayout do a conditional rendering of each component. Something like this:

{currentTheme === 'fancy' && <FancyTheme/>}

The component has to be used inside the <head> tag.

#

It works but it seems like a hack