Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Svelte: Is there a way to make global css variables in scope of svelte components?

I have set my global.css file which I import in index.js

--root {
  --main-color: red;
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

index.js

import "./global.css";
import App from "./App.svelte";

const app = new App({
  target: document.body
});

My webpack setup

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
  entry: "./src/index.js",
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "dist")
  },
  module: {
    rules: [
      {
        test: /\.(html|svelte)$/,
        exclude: /node_modules/,
        use: {
          loader: "svelte-loader",
          options: {
            emitCss: true,
            hotReload: true
          }
        }
      },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: { loader: "style-loader", options: { sourceMap: true } },
          use: [
            { loader: "css-loader", options: { sourceMap: true } },
            {
              loader: "postcss-loader",
              options: {
                sourceMap: true,
                ident: "postcss",
                plugins: loader => [
                  require("postcss-import")({}),
                  require("postcss-preset-env")(),
                  require("cssnano")()
                ]
              }
            }
          ]
        })
      }
    ]
  },
  plugins: [new HtmlWebpackPlugin(), new ExtractTextPlugin("styles.css")]
};


Works perfect for setting up global css for the entire app. But I am trying to use the --main-color in my svelte components. Is there a way to inject them down to all the components' css ?

Since I import global.css first, it should work as it emits a file with --root{} first then rest of the component styles.

like image 322
frank3stein Avatar asked May 10 '19 19:05

frank3stein


2 Answers

Print code below in main component

:global(:root){
   --header-color: purple
}

into you other file just use it:

h1{
      color: var(--header-color);
     }
like image 109
Ivan Afanasyev Avatar answered Oct 19 '22 11:10

Ivan Afanasyev


I was busy with this, trying different webpack settings etc., seeing that the output css should work, I just could not find why it did not work. I wrote the post before trying for one last time, which wasted another hour. I finally found the error.

Instead of using :root{} I have mistyped it --root{}. I have posted it anyways, in case someone is stuck with the same mistake.

like image 27
frank3stein Avatar answered Oct 19 '22 10:10

frank3stein