In the world of web development, CSS is the language used to style and design web pages. However, as web projects become more complex and sophisticated, developers often find themselves grappling with the challenges of maintaining large CSS codebases. This is where SCSS (Sass) comes into play. SCSS, an acronym for "Sassy CSS," is a popular CSS preprocessor that offers a range of powerful features and enhancements over traditional CSS.

Using SCSS can greatly enhance the development experience by providing a more efficient and maintainable way to write CSS. It introduces features like variables, nesting, mixins, inheritance, and modular imports, which empower developers to write cleaner and more concise stylesheets. SCSS also offers advanced functions and control structures that allow for dynamic styling and code reusability.

Comparison between SCSS and CSS

Comparison between SCSS and CSS

In this article, we will explore how to bundle SCSS files with webpack, enabling us to take advantage of the powerful features and benefits that SCSS offers. Let's dive in and discover the world of SCSS with webpack:

  1. Install the necessary dependencies:

    pnpm add -D sass-loader sass
    

    sass-loader is a webpack loader that allows us to preprocess Sass/SCSS files. It takes Sass/SCSS code as input and transforms it into valid CSS code that can be understood by the browser. When sass-loader processes a Sass/SCSS file, it compiles the Sass/SCSS syntax into regular CSS code. It applies transformations, such as resolving imports, evaluating variables, expanding mixins, and handling nested selectors, to generate the final CSS output.

  2. We can combine the sass-loader with the css-loader and the mini-css-extract-plugin to extract the styles into a separate file. This allows us to configure webpack to handle Sass files, process them with the Sass loader, and then extract them into a standalone CSS file.

    const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
    const HtmlWebpackPlugin = require('html-webpack-plugin')
    const MiniCssExtractPlugin = require('mini-css-extract-plugin')
    const { PurgeCSSPlugin } = require('purgecss-webpack-plugin')
    const TerserPlugin = require('terser-webpack-plugin')
    const path = require('path')
    
    module.exports = {
      entry: './src/index.js',
      module: {
        rules: [
          {
            test: /\\.scss$/,
            use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
          },
        ],
      },
      optimization: {
        minimizer: [new CssMinimizerPlugin(), new TerserPlugin()],
      },
      output: {
        filename: 'main.js',
        path: path.resolve(__dirname, '../dist'),
      },
      plugins: [
        new HtmlWebpackPlugin({
          filename: 'index.html',
          template: './src/index.html',
        }),
        new MiniCssExtractPlugin({
          filename: 'index.css',
        }),
        new PurgeCSSPlugin({
          paths: ['./src/index.html'],
        }),
      ],
    }
    
  3. Rename the src/index.css file to src/index.scss file. Create a SASS variable to store the max width of our html.

    /* <https://www.swyx.io/css-100-bytes> */
    
    $mw: 70ch;
    
    html {
      max-width: $mw;
      padding: 3em 1em;
      margin: auto;
      line-height: 1.75;
      font-size: 1.25em;
    }
    
    .font-bold {
      font-weight: 700;
    }
    
  4. Change the import of our styles in src/index.js file from index.css to index.scss.

    import './index.scss'
    
    const form = document.getElementById('add-form')
    const output = document.getElementById('result')
    
    const foo = 'bar'
    
    function multiply(nums) {
      const result = nums.reduce((acc, num) => acc * num, 1)
      return result
    }
    
    function sum(nums) {
      const result = nums.reduce((acc, num) => acc + num, 0)
      return result
    }
    
    form.addEventListener('submit', (e) => {
      e.preventDefault()
      const { first, second } = e.target.elements
      const result = sum([+first.value, +second.value])
      output.innerText = `Total = ${result}`
    })
    
  5. Run the webpack build command.

Conclusion

That's it! We have now set up webpack to bundle SCSS files. By incorporating SCSS into our webpack workflow, we can streamline our CSS development, enhance code maintainability, and unlock the full potential of modern CSS styling.

Resources

Sass: Documentation