Output 2 (or more) .css files with mini-css-extract-plugin in webpack

半世苍凉 提交于 2019-12-03 03:58:13

This Example also complies the SCSS and doesn't use MiniCssExtractPlugin

In Webpack 4.16.5 I have managed to get this to work by first installing these 2 packages

npm install --save-dev file-loader
npm install --save-dev extract-loader

Then in your webpack.config.js

//const MiniCssExtractPlugin = require("mini-css-extract-plugin");

var path = require("path");

module.exports = {
    entry: ['./blocks.js','./block.editor.scss','./block.style.scss'],
    mode: 'production',//change to 'development' for non minified js
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: 'blocks.build.js',
        publicPath: "/dist"
    },
    watch:true,
    module: {
        rules: [
            {
                test: /.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
            },
            {
                test: /\.scss$/,
                use: [  
                    {
                        loader: 'file-loader',
                        options: {
                            name: '[name].build.css',
                            context: './',
                            outputPath: '/',
                            publicPath: '/dist'
                        }
                    },
                    {
                        loader: 'extract-loader'
                    },
                    {
                        loader: 'css-loader',
                    },
                    {
                        loader: 'sass-loader',
                        options: {
                            sourceMap: true
                        }
                    }
                ]
            },
        ],
    },
};

This will output the following structure

- dist
--- block.editor.build.css
--- block.style.build.css
--- blocks.build.js

- blocks.js
- block.editor.scss
- block.style.scss

To minifi the CSS install

npm install --save-dev uglifyjs-webpack-plugin
npm install --save-dev optimize-css-assets-webpack-plugin

add to webpack.config.js

const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");

var path = require("path");

module.exports = {
    .....
    watch:true,
    module: {
        rules: [
            .....
        ],
    },
    optimization: {
        minimizer: [
          new UglifyJsPlugin({
            cache: true,
            parallel: true,
            sourceMap: true // set to true if you want JS source maps
          }),
          new OptimizeCSSAssetsPlugin({})
        ]
    },
};

Hope this helps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!