Skip to content

Instantly share code, notes, and snippets.

@theetrain
Created June 21, 2024 02:42
Show Gist options
  • Save theetrain/829f1a06119d630d4d32b9eaa5936ada to your computer and use it in GitHub Desktop.
Save theetrain/829f1a06119d630d4d32b9eaa5936ada to your computer and use it in GitHub Desktop.
Automatically import library CSS with Svelte components

Cool Vite thing I learned today; @import in .css files will be inlined at build time.

/* main.css */
@import url('variables.css');
@import url('normalize.css');

This becomes a single CSS file in the production build; and if you happen to add it to a shared library (npm package), you can have it auto-import global styles along with Svelte components.

// example-library/src/index.js
import './main.css'
export { default as Button } from './Button/Button.svelte'
<!-- +page.svelte -->
<script>
  // `main.css` is automatically imported with this module
  // and `@import`s are inlined at build time
  import { Button } from 'example-library'
</script>

<Button>Let's go</Button>

I suppose one pitfall could occur when the library isn't used in your root layout. If one page doesn't use the library, then it won't have the global CSS loaded at first page load, until you navigate to a page that does use a library component.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment