If you want to achieve this functionality, there are two main approaches you can take. The first method mentioned is not compatible with Internet Explorer.
With the latest version of CSS outlined on the W3C website, variables can now be directly incorporated into CSS.
For instance, a backend can implement something similar to:
<head>
<style type="text/css">
:root {
--primary-color: #cecece;
--secondary-color: #fefefe;
}
</style>
</head>
Subsequently, in your scss (or css) file, you can use:
.mySelector {
color: var(--primary-color, black);
}
This code snippet will essentially render as:
.mySelector {
color: #cecece;
}
The color will fallback to `black` if `--primary-color` is undefined.
By utilizing these methods, it becomes easy for the backend to configure settings for the frontend. Meanwhile, from the frontend perspective, existing tools in the CSS API can be easily utilized.
However, if compatibility with IE is necessary, a more intricate infrastructure may be required.
The objective is to trigger webpack sass compilation every time a user changes their color selection, resulting in a generated css output with the relevant variable configurations.
To accomplish this, the use of Sass resource loader would be essential, automatically injecting sass files into all other files, akin to adding `@import "_colors"` automatically.
Following this, the backend server would need to:
- Create an _color.scss file at a specified location, e.g. /user/123/_color.scss
- Request compilation using `webpack client 123`
- Check the output webpack folder for client 123 and verify the presence of specific CSS files
- Inject them into the head section of HTML
In terms of webpack configuration,
Your webpack setup might include:
const argv = require("yargs").argv;
entry: {
[...]
},
output: {
// Use the argument as clientId to create a dedicated output folder
path: helpers.root(`public/themes/front/${argv.client}`),
filename: "[name].[contenthash].js",
chunkFilename: "[name].[contenthash].js"
}
This way, based on the client id provided, the resulting CSS will be stored in a specific directory.
Finally, the SaSS rules could look like this:
{
test: /\.scss$/,
use: [
'style-loader',
'css-loader',
'postcss-loader',
'sass-loader',
{
loader: 'sass-resources-loader',
options: {
resources: (argv.client) ? `/user/${ argv.client }/_color.scss` : `/user/default/_color.scss`,
},
},
],
}