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

frank3stein picture frank3stein · May 10, 2019 · Viewed 8.9k times · Source

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.

Answer

Ivan Afanasyev picture Ivan Afanasyev · Jul 17, 2019

Print code below in main component

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

into you other file just use it:

h1{
      color: var(--header-color);
     }