Webpack compile scss to css and minify

25,865

Solution 1

If you simply want to be able to import .scss files from your Javascript modules and have it directly applied to the DOM, you can simply follow this documentation first:

https://webpack.js.org/loaders/sass-loader/

and then add Postcss to the mix:

https://github.com/postcss/postcss-loader

tldr;

npm install sass-loader node-sass style-loader css-loader postcss-loader cssnano --save-dev
// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [
          'style-loader', // creates style nodes from JS strings
          {
            loader: 'css-loader', // translates CSS into CommonJS
            options: {
              importLoaders: 1
            }
          },
          'postcss-loader', // post process the compiled CSS
          'sass-loader' // compiles Sass to CSS, using Node Sass by default
        ]
      }
    ]
  }
};
// postcss.config.js
module.exports = {
  plugins: {
    'cssnano': {}
  }
};

If you want to extract the compiled CSS into a separate file, there is:

https://github.com/webpack-contrib/mini-css-extract-plugin

Especially:

https://github.com/webpack-contrib/mini-css-extract-plugin#advanced-configuration-example

Solution 2

You can use mine config to do that. I'm using optimize-css-assets-webpack-plugin

You can view my full config here

const path = require("path");
const webpack = require("webpack");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CompressionPlugin = require("compression-webpack-plugin");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const WebpackShellPlugin = require('webpack-shell-plugin');
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");

process.traceDeprecation = true;

module.exports = {
    output: {
        path: path.resolve(__dirname, "wwwroot/dist"),
        filename: "[name].js",
        publicPath: "/dist/"
    },
    optimization: {
        minimizer: [
            new UglifyJsPlugin({
                cache: true,
                parallel: true,
                sourceMap: false,
                extractComments: 'all',
                uglifyOptions: {
                    compress: true,
                    output: null
                }
            }),
            new OptimizeCSSAssetsPlugin({
                cssProcessorOptions: {
                    safe: true,
                    discardComments: {
                        removeAll: true,
                    },
                },
            })
        ]
    },
    plugins: [
        new webpack.ContextReplacementPlugin(/\.\/locale$/, 'empty-module', false, /jsx$/),
        new webpack.LoaderOptionsPlugin({
            options: {}
        }),
        new MiniCssExtractPlugin({
            filename: "[name].css",
            chunkFilename: "[id].css"
        }),
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            Popper: ['popper.js', 'default']
        }),
        new CompressionPlugin({
            test: /\.(js|css)/
        }),
        new UglifyJsPlugin(),
        new WebpackShellPlugin({
            onBuildStart: ['echo "Starting postcss command"'],
            onBuildEnd: ['postcss --dir wwwroot/dist wwwroot/dist/*.css']
        })
    ],
    resolve: {
        modules: [
            path.resolve('./React/js/App'),
            path.resolve('./React/js/App/Modules/Client'),
            path.resolve('./React/js/App/Modules/Adnmin'),
            path.resolve('./node_modules')
        ]
    },
    module: {
        rules: [{
                test: /\.scss$/,
                use: [
                    'style-loader',
                    MiniCssExtractPlugin.loader,
                    {
                        loader: "css-loader",
                        options: {
                            minimize: true,
                            sourceMap: true
                        }
                    },
                    {
                        loader: "sass-loader"
                    }
                ]
            }
        ]
    }
};

But I would recommend you using postcss to minify css. I'm using WebpackShellPlugin to run minify command

Share:
25,865
Admin
Author by

Admin

Updated on July 24, 2022

Comments

  • Admin
    Admin almost 2 years

    I am new with webpack and I am struggling how to convert scss to css and then minify.

    File structure

     📦public
         ┣ 📂dist
         ┃ ┣ 📂css
         ┃ ┗ 📂js
         ┃ ┃ ┗ 📜adminMain.js
         ┣ 📂src
         ┃ ┣ 📂css
         ┃ ┃ ┃ ┣ 📜admin.css
         ┃ ┃ ┃ ┣ 📜admin.css.map
         ┃ ┃ ┃ ┣ 📜admin.scss
         ┃ ┃ ┃ ┣ 📜main.css
         ┃ ┃ ┃ ┣ 📜main.css.map
         ┃ ┃ ┃ ┗ 📜main.scss
         ┃ ┗ 📂js
         ┃ ┃ ┗ 📜adminMain.js
    

    I am compiling js like this

    "dev": "webpack --mode development ./public/src/js/adminMain.js --output ./public/dist/js/adminMain.js",
    "build": "webpack --mode production ./public/src/js/adminMain.js --output ./public/dist/js/adminMain.js"
    

    I found thing like sass-loader but cant make it work.

    webpack.config.js

    module.exports = {
        module: {
            rules: [{
                test: /\.scss$/,
                use: [{
                    loader: "sass-loader",
                    options: {
                        minimize: true
                    }
                }]
            }]
        }
    };
    

    i dont know where to put path to included file and where to put path to output.

    I will be thankfull for any advice.

  • Tony Ngo
    Tony Ngo almost 5 years
    That's just like my recommend
  • Razvan Zamfir
    Razvan Zamfir about 2 years
    Please help me with this question. Than you!