Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am trying to import SASS variables into my javascript file

I an attempt to get my .js file to see SASS variables, I've followed this article. This question features an error I get from attempting this method. But even if you have had success importing SASS variables in javascript in another way, please do share your success with me!

I will show you the code I've written and the error I get. First the code:

My webpack.config.js file:

module.exports = {

    entry: `./sass.js`, 
    output: {
      path: `${__dirname}`, 
      filename: 'bundle.js'
    },
    mode: 'development',

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

My .scss file:


$kiwi: red;

:export {
    kiwi: $kiwi,
}

My .js file:

import variables from './webpack_sass.scss';

My .html file (which I've checked does correctly see bundle.js):

<head>
  <script type="module" src="./bundle.js"></script>
</head>

I have installed webpack & webpack-cli. Here's a picture of my package.json file:

enter image description here

The error I get is:

enter image description here


like image 792
tonitone120 Avatar asked Sep 03 '25 08:09

tonitone120


1 Answers

:export syntax is a sugar that css-loader adds, all you need to do is to enable the css-modules feature.

You have 2 choices:

  1. add .module.scss suffix to your file (since css-module is enabled by default for it)
  2. enable css-modules to all .scss imports, by specifying
// webpack.config.js

module.exports = {
  entry: `./sass.js`,
  output: {
    path: `${__dirname}`,
    filename: 'bundle.js',
  },
  mode: 'development',

  // ...
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              modules: true, // <- this enables css-modules for all imports
            },
          },
          'sass-loader',
        ],
      },
      // ...
    ],
  },
};
like image 87
felixmosh Avatar answered Sep 04 '25 22:09

felixmosh