Skip to content

ryoppippi/svelte-preprocess-import-css

Repository files navigation

svelte-preprocess-import-css

JSR JSR

This is a Svelte preprocessor that allows you to import scoped CSS files into your Svelte components. Based on this issue

Usage

You can add it to your svelte.config.js, then add it to the preprocessor list:

import { importCSSPreprocess } from '@ryoppippi/svelte-preprocess-import-css';
export default {
  preprocess: [
    importCSSPreprocess(), // <--
    svelteAutoPreprocess(),
  ],
};

Now you can use @import "./whatever.css" scoped;.

For example, the following CSS:

<style>
@import "./a.css" scoped;
@import "./b.css" scoped;

.another-style { display: block }
</style>

will get converted into:

<style>
contents of a.css will be here
contents of b.css will be here

.another-style { display: block }
</style>

Select Style Rules by Query Selector

You can select style rules by query selector.

For example, the following CSS and Svelte:

/* a.css */

div { color: red; }

.message { color: blue; }
<div> hello </div>
<p class="message"> world </p>

<style>
@import "./a.css?.message" scoped;

div { color: green; }
</style>

will get converted into:

<div> hello </div>
<p class="message"> world </p>

<style>
.message { color: blue; }

div { color: green; }
</style>

Rename Style Rules by Query Selector

You can rename style rules by query selector.

For example, the following CSS and Svelte:

/* a.css */

div { color: red; }

.m0 { color: blue; }
<p class="m1"> world </p>

<style>
@import "./a.css?.m0=.m1" scoped;

div { color: green; }
</style>

will get converted into:

<p class="m1"> world </p>

<style>
.m1 { color: blue; }

div { color: green; }
</style>

License

MIT