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?
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With