I followed this post How to use SCSS variables into my React components or this one React and SCSS export a variable from scss to react to get scss variable in my react app but it does not work.
myvar.scss file:
$color: red;
:export {
color: $color;
}
.myclass {
background-color: $color;
}
App.js file:
import variables from './myvar.scss';
const App = () => {
console.log(variables);
return <div className="myclass">Hello</div>
}
export default App;
The div background is red, so myvar.scss is working. But variables
is an empty object.
(react version : 17.0.1)
node_modules\react-scripts\config\webpack.config.js
module: {
strictExportPresence: true,
rules: [
{ parser: { requireEnsure: false } },
{
oneOf: [
...
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
},
'sass-loader'
),
sideEffects: true,
},
UPDATE: The original answer claims that it is only supported by webpack, but this is no longer true. Many bundlers now support this via their own css processing pipeline.
Original Answer: That's a webpack/css-loader feature and only works with webpack and css-loader (https://webpack.js.org/loaders/css-loader/#separating-interoperable-css-only-and-css-module-features)
Important: the
:export
syntax in your SCSS/CSS files will only work for those files that are treated as a module by css-loader, because this syntax is part of a css module proposal. You can...foostyle.module.scss
loader: 'css-loader', options: { modules: true }
A blogpost with an example can be found here: https://til.hashrocket.com/posts/sxbrscjuqu-share-scss-variables-with-javascript (Be aware that the blogpost doesn't mention the fact that css modules must be used.)
and
your webpack.config.js will probably contain a chain of loaders with
css-loader
as last or second-to-last (process-chronologically speaking) and this should work.