Home > Software design >  why the scss file need different type of loader
why the scss file need different type of loader

Time:01-25

Now I read the config that package the scss file write like this:

{
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
      {
        test : /\.(scss)$/ ,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: "css-loader",
            options: {
              modules: true,
              sourceMap: true
            }
          },
          "sass-loader"
        ]
      }

why the scss file need 3 type of loader? what is the parse process? first using MiniCssExtractPlugin.loader then css-loader and finnally sass-loader? why did not using the only one sass-loader to parse the scss file?

CodePudding user response:

Each loader do only one simple work:

  1. the sass-loader compile the Sass to pure CSS string. But can't save it into a CSS file.
  2. the css-loader "catch" the compiled CSS string and export as JS module to handle it in additional loaders. The loader can't save a CSS file.
  3. the MiniCssExtractPlugin.loader is a middleware for own plugin. It do not others as "catch" JS module from css-loader and pass it into plugin MiniCssExtractPlugin.
  4. The plugin MiniCssExtractPlugin extract the pure CSS string and save it as CSS file.

NOTE: Webpack generate a js file for each resource defined in webpack entry.
The mini-css-extract-plugin extract css, but not eliminate a generated empty js file.
To remove unexpected empty js file use the plugin webpack-remove-empty-scripts.

The minimal webpack.config.js to extract css from scss.

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const RemoveEmptyScriptsPlugin = require('webpack-remove-empty-scripts');

module.exports = {
    entry: {
        'styles': './assets/scss/styles.scss',
    },
    module: {
        rules: [
            {
                test: /\.(scss)$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    {
                        loader: "css-loader",
                        options: {
                            modules: true,
                            sourceMap: true
                        }
                     },
                     'sass-loader',
                ]
            },
        ]
    },
    plugins: [
        new RemoveEmptyScriptsPlugin(), // <== remove empty js files
        new MiniCssExtractPlugin({
            filename: '[name].[chunkhash:8].css', // <== save CSS file
        }),
    ],
};
``
  •  Tags:  
  • Related