css modules & cssnext custom properties in react + webpack

2.2k Views Asked by At

I am just wondering what would be the best approach to using cssnext custom properties like these, alongside css modules in react.

Is there a way to share these across modules ?

:root{
  --primary: pink;
  --fontSize: 1rem;
  --fullWidth: 100%;
  --color: red;
  --gutter: 1.618rem;
}
@custom-media --small-viewport (max-width: 30em);
@custom-media --large-viewport (min-width: 75em);
@custom-media --only-medium-screen (width >= 500px) and (width <= 1200px);

EDIT: *** ok i tried this, thought it worked but hasn't

:global(:root) {
  --primary: pink;
  --fontSize: 1rem;
  --fullWidth: 100%;
  --color: pink;
  --gutter: 1.618rem;
}
2

There are 2 best solutions below

1
On

CSS Modules should only handle selectors that are classnames (that start with a dot). So it should not be an issue and you should be able to use those custom definition as soon as they are in the file. You can use postcss-import to inline your file that contains global definitions.

Another solution is to define this global values using postcss plugin options:

0
On

Because the postcss-loader only transforms a single file at a time you must import your custom properties, e.g.

@import './root.css';

.foo {
    color: var(--primary);
}