ls-age / svelte-preprocess-sass

Svelte preprocessor for sass
91 stars 6 forks source link

Style overrides #95

Open dm-de opened 4 years ago

dm-de commented 4 years ago

FEATURE REQUEST

Lets say i write ui library package. I can define some variables (colors etc) for my theme and import values in all components.

Someone else want to use my library. But he need to modify/fork my lib.

Now my idea: What if this preprocesser look for a custom style file in project root and override original package variable values (only in memory, files are untouched).

So custom vars have higher priority than original package vars. Is this possible?

Same idea for LESS?

LukasHechenberger commented 4 years ago

First of all, thanks for the input!

I don't think it's this package's responsibility to load additional styles as it's not necessary in all use cases. But maybe you want to use node-sass's includePaths option to override a theme file:

Assuming you provide styles via a package published as my-lib on npm

You can provide variables and default variables in a file called theme.scss (note the !default):

// theme.scss inside the 'my-lib' package
$primary: red !default;
$primary-inverted: white !default;

To import these, add _nodemodules to includePaths:

// rollup.config.js
import { join } from 'path';
import svelte from 'rollup-plugin-svelte';
import { sass } from 'svelte-preprocess-sass';

export default {
  // ...
  plugins: [
    svelte({
      preprocess: {
        style: sass(
          {
            includePaths: [
              // Allow imports from 'node_modules'
              join(__dirname, 'node_modules'),
            ],
          },
          { name: 'scss' }
        ),
      },
    }),
  ],
};

In svelte components, import the theme file:

<!-- src/components/Button.svelte -->
<style type="text/scss">
  @import 'my-lib/theme.scss';

  button {
    background-color: $primary;
    color: $primary-inverted;
  }
</style>

<button on:click>Click me</button>

As of now, your component renders a button with a red background and white text.

So, now you want to override these theme styles

Add another include path:

// rollup.config.js
sass({
  includePaths: [
    // Allow imports from 'src/styles/overrides'
    './src/styles/overrides',

    // Allow imports from 'node_modules'
    join(__dirname, 'node_modules'),
  ],
});

And provide an override stylesheet for my-lib:

// src/styles/overrides/my-lib/theme.scss
$primary: blue;

// Import original theme
@import '../../../../node_modules/my-lib/theme.scss';

As a result your component will be rendered with a blue background and a white text color.

LukasHechenberger commented 4 years ago

If you want to play around with it:

https://github.com/LukasHechenberger/sample-svelte-scss-lib