How to enable sass modules in webpack 4?

by giovanny.lueilwitz , in category: Javascript , a year ago

How to enable sass modules in webpack 4?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by muriel.schmidt , a year ago

@giovanny.lueilwitz 

To enable Sass modules in Webpack 4, you can follow these steps:

  1. Install the necessary packages:
1
npm install sass sass-loader style-loader css-loader --save-dev


  1. Create a styles folder in your project's root directory, and inside it, create your Sass module file (e.g., styles.module.scss). Import any relevant styles or define your styles within this file.
  2. Update your Webpack configuration file (webpack.config.js) to include the Sass loader:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
module.exports = {
  // ...
  module: {
    rules: [
      // ...
      {
        test: /.module.scss$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              modules: true // Enable CSS modules
            }
          },
          'sass-loader'
        ]
      },
      // ...
    ]
  },
  
  // ...
};


  1. Import and use your Sass module in your JavaScript code:
1
2
3
4
import styles from './styles.module.scss';

// Use the styles object to access your styled classes
console.log(styles.exampleClass);


  1. Run your Webpack build process, and your Sass modules should now be enabled.


Note: Make sure that you update the file extensions and paths according to your project's structure.