postcss / postcss-custom-properties

Use Custom Properties in CSS
https://postcss.github.io/postcss-custom-properties
MIT License
597 stars 77 forks source link

insert importedFrom into :root #155

Closed RedHatter closed 5 years ago

RedHatter commented 5 years ago

I have a setup where I generate variables through a script then inject them using importedFrom. Unfortunately, postcss-custom-properties doesn't inject the newly generated variables into the :root declaration.

// generate.js
module.exports = {
  customProperties: { '--main': 'red' }
}
postcssCustomProperties({
  importFrom: 'generate.js'
});

Input css

a {
  color: var(--main);
}

Output css

a {
  color: red;
  color: var(--main);
}

What I would like

:root {
  --main: red;
}

a {
  color: red;
  color: var(--main);
}
jonathantneal commented 5 years ago

Yes, that is not a out-of-the-box feature of this project. However, you can use the exportTo option to insert those variables into a generated file.

https://github.com/postcss/postcss-custom-properties#exportto

oliverjam commented 5 years ago

Sorry to comment on a closed issue but I just hit the same confusion and thought it'd be better than opening a new one.

It feels like the out-of-the-box behaviour is a bit unexpected here. For example in browsers that support custom properties the above example is broken, since the browser will ignore the inlined color: red and try to use color: var(--main), which doesn't exist on the page.

I'm not sure how exportTo solves this either—do you mean we should export to a file, then import that file wherever we need access to custom properties from :root?

I think possibly I'm misunderstanding the purpose of importFrom—I assumed it was to provide access to global variables from a single place without having to import them in every file.

jonathantneal commented 5 years ago

@oliverjam, yes, importFrom does exactly that. It doesn’t presume you’re processing a mono CSS file — :root could exist in another file not being processed. If, however, you are importing variables in a non-CSS-standard fashion from JS, then you ought to explicitly export them back to CSS using the exportTo option.

jonathantneal commented 5 years ago

To help me stay focused, feel free to open a new issue if you’ve found a bug or have a specific issue with this rationale.