如何从Webpack 4中的单个JS文件输出多个CSS文件?

时间:2018-12-24 19:59:45

标签: webpack webpack-4 mini-css-extract-plugin

在我的js文件“ example.js”中,我想分别为网站的桌面版和移动版导入两个.scss文件“ example.scss”和“ example.m.scss”。所以我需要三个输出-example.js,example.scss和example.m.scss。如何在Webpack 4中上线?

JS文件:

// CSS
import '../../css/example.scss';
import '../../css/mobile/example.m.scss';

我当前的Webpack配置:

const path = require('path');
const webpack = require("webpack");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
    entry: {
        home: './src/AppBundle/Resources/public/js/main_home/main_home.js',
       // ...
    },

    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'web/assets'),
    },

    module: {
        rules: [
            {
                test: /\.scss|.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    "css-loader", // translates CSS into CommonJS
                    "sass-loader" // compiles Sass to CSS, using Node Sass by default
                ]
            },
            {
                test: /\.(png|jpg|jpeg|gif)$/,
                use: ['file-loader'],
            },
            {
                test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
                use: [{
                    loader: 'file-loader'
                }]
            }
        ]
    },

    plugins: [
        new MiniCssExtractPlugin({
            filename: "[name].css",
        }),

        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            'window.$': 'jquery',
            'window.jQuery': 'jquery'
        })
    ]
};

1 个答案:

答案 0 :(得分:0)

假设您不想为第二个CSS捆绑包添加第二个js入口点,请参见此处的示例: https://github.com/webpack-contrib/mini-css-extract-plugin/issues/45#issuecomment-425645975

正确设置有点棘手。