Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i have a single variables file using cssnext with webpack?

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?

like image 224
Michael Willmott Avatar asked Feb 03 '16 10:02

Michael Willmott


2 Answers

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);
}
like image 130
Athyuttam Eleti Avatar answered Oct 12 '22 09:10

Athyuttam Eleti


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.

like image 34
Danyil Velichko Avatar answered Oct 12 '22 10:10

Danyil Velichko