Skip to content
This repository has been archived by the owner on Feb 21, 2022. It is now read-only.

A custom Svelte preprocessor to add support for style directive.

License

Notifications You must be signed in to change notification settings

sidx1024/svelte-style-directive

Repository files navigation

Archive Note

Archived because Svelte added support for style directives.

npm version

What is it?

A custom Svelte preprocessor to add support for style directive.

<span
  style:font-size="16px"
  style:color={color}
  style:text-transform="lowercase"
  >

Usage

Add to package.json

npm i --save-dev svelte-style-directive

Add to rollup.config.js

import svelte from 'rollup-plugin-svelte'
import { svelteStyleDirective } from 'svelte-style-directive'

export default {
  plugins: [
    svelte({
      preprocess: [
        svelteStyleDirective()
      ]
    })
  ]
}

Why?

It's very convenient to apply classes based on state/prop in Svelte.

<script>
  let hidden = false;
  let bold = true;
</script>

<style>
  .hidden {
    display: none;
  }
  .bold {
    font-weight: bold;
  }
</style>

<span class:hidden={hidden} class:bold={bold}>Heading</span>

class directive makes things much easier. But, what if you wanted to make this work with style attributes? This plugin adds support style directive to achieve similar functionality.

So you can do this:

<script>
  let bold = true;
  let color = 'red';
</script>

<span style:font-weight={bold} style:color={color}>Heading</span>

instead of this:

<script>
  let bold = true;
  let color = 'red';
</script>

<span style={`${bold ? 'font-weight: bold; ' : ''}${color ? 'color: red; ' : ''}`}>Heading</span>

It also works for CSS Variables!

Performance

As this is a preprocessor, it is just a syntactic sugar. It has no runtime overhead.

Examples

Using state

<script>
  let progress = 0.5;
</script>

<!-- Without style directive -->
<div class="progress-bar">
  <div class="cursor" style={`left: ${progress * 100 + '%'};`}></div>
</div>

<!-- With style directive -->
<div class="progress-bar">
  <div class="cursor" style:left={progress * 100 + '%'}></div>
</div>

<!-- Assume styles for progress-bar and cursor are already declared -->

CSS variables

<script>
  let textColor = '#9c9c9c';
</script>

<style>
  span {
    color: var(--text-color);
  }
</style>

<div style:--text-color={textColor}>
  <span>Some text with color</span>
</div>

About

A custom Svelte preprocessor to add support for style directive.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published