How to get SCSS variables in js code (nodejs server)?

1.2k Views Asked by At

From this blogpost example https://til.hashrocket.com/posts/sxbrscjuqu-share-scss-variables-with-javascript, I tried to get scss variables in my js code and I did not manage to do it.

index.js file

import variables from './variables.scss';
console.log(variables);

variables.scss file

$myvar: 100;

:export {
  myvar: $myvar;
}

webpack.config.js file

module.exports = {
  mode: 'development',
  module: {
    rules: [{
        test: /\.scss$/,
        use: [{
          loader: "style-loader"
        }, {
          loader: 'css-loader'
        }, {
          loader: 'sass-loader'
        }]
    }]
  }
};

dependencies in package.json file

  "dependencies": {
    "css-loader": "^5.0.2",
    "lodash": "^4.17.20",
    "postcss-loader": "^5.0.0",
    "sass": "^1.32.6",
    "sass-loader": "^11.0.1",
    "style-loader": "^2.0.0",
    "webpack": "^5.21.2",
    "webpack-cli": "^4.5.0"
  }

Compilation : npx webpack
Output :

asset main.js 17.2 KiB [compared for emit] (name: main)  
runtime modules 937 bytes 4 modules  
cacheable modules 9.23 KiB  
  modules by path ./src/ 1020 bytes  
    ./src/index.js 324 bytes [built] [code generated]  
    ./src/variables.scss 371 bytes [built] [code generated]  
    ./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js!./src/variables.scss 325 bytes [built] [code generated]  
  modules by path ./node_modules/ 8.23 KiB  
    ./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js 6.67 KiB [built] [code generated]  
    ./node_modules/css-loader/dist/runtime/api.js 1.57 KiB [built] [code generated]  
webpack 5.21.2 compiled successfully in 503 ms

In the web console, the object variables is empty and of course, I could not use variables.myvar.
Is there a configuration problem in webpack.config.js ? I tried to simplify it as much as possible. All node_modules are up to date and npm version is 6.14.9.

Thanks for help.

1

There are 1 best solutions below

4
On BEST ANSWER

I wasn't aware of it but maybe this only works for "css modules". I never tried it without having css-loader configured to be module based. (you can see in my config in this answer that modules are activated) Please try the following: rename your variables.scss into variables.module.scss Because by default the css-loader will treat your files as modules or not as modules based on the filename (https://webpack.js.org/loaders/css-loader/#modules).