Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
882 views
in Technique[技术] by (71.8m points)

node.js - How to get SCSS variables into react

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 eact-scriptsconfigwebpack.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,
        },
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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...

  • either use the default behavior of css-loader and trigger that behavior via filename: e.g. foostyle.module.scss
  • or you can configure css-loader to treat all files as modules e.g. 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.)

$white-color: #fcf5ed;

:export {
  whitecolor: $white-color;
}

and

import variables from 'variables.module.scss';

console.log(variables.whitecolor)

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.

module: {
    rules: [
      {
        test: /.scss$/,
        use: [ 'style-loader', 'css-loader', 'sass-loader' ],
      },

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...