10

I've got a project which has a set of css files (one for each react component). I'm using the css-loader (with modules on) in webpack and also postcss-cssnext.

Ideally i want a single variables.css so i can share variables across the css files. I've tried having variables.css containing something like:

:root {
  --gutter-width: 1rem;
  --outer-margin: 2rem;
  ...
}

which i then import so it goes through the css loader. The problem is, other files don't pick up on these variables, so either this doesn't work or i'm doing something wrong (including this in the component css file directly does work).

One thing that does work is having a styles.json file with the following webpack setup:

postcss: function (webpack) {
    return [
        ...
        require("postcss-cssnext")({
          features: {
            customProperties: {
              variables: require('./src/styles.json')
            }
          }
        })
        ...
    ]
}

The main problem with this though is every time i change a variable i have to restart the webpack dev server (so reloading the webpack config). This isn't ideal.

So, any thoughts on a better way to do this?

2 Answers 2

6

Using postcss-import is the way to go. Here's a sample config using CSS modules:

{ 
  test: /\.css$/,
  loader: ExtractTextPlugin.extract(
    "style",
    "css?modules&localIdentName=[name]--[local]&sourceMap&importLoaders=1!postcss"
  )
}

And in your postcss settings:

postcss: [
  require("postcss-import")({
    path: baseDir,
    addDependencyTo: webpack
  }), 
  require("postcss-cssnext")
]

The path setting tells postcss-import to resolve paths by also looking into the directories specified here.

And finally, in your CSS module file, say Button.css:

@import "styles/constants/constants.css";

.normal {
  font-size: 24px;
  color: var(--figmaBlue);
}
2
  • is postcss-import really necessary? can't webpack just parse the @import CSS at-rule itself?
    – Hristo
    Jan 6, 2017 at 3:00
  • @Hristo sorry, but I haven't worked with this stack in months and have lost context. Jan 7, 2017 at 9:42
2

Variables (at least at the moment) are not shared across imported css files in cssnext-loader, even if you put them into :root {}.

The simples solution that I've found is to use postcss-import plugin before postcss-cssnext. After setting it up you will need to
@import 'variables.css';
inside .css files where you want to access those variables.

1
  • 1
    Do you have a working example for this? This is the same exact issue I am having, as well. Thank you!
    – Detuned
    Jun 5, 2016 at 0:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.