Webpack building both css and js files

my problem is that webpack builds both js and css files when the input is sass file. Here is what webpack outputs. I just want css files to be outputed for scss, not both. I do not know how to do that. I hope someone can help. Here is my code.

let path = require("path");
let webpack = require("webpack");
let ExtractTextPlugin = require("extract-text-webpack-plugin");

let SRC = path.join(__dirname, "client", "src");
let DIST = path.join(__dirname, "client", "dist", "bundles");

module.exports = [{
    entry: {
        admin: SRC + "/js/admin/index.js",
        main: SRC + "/js/main/index.js",
        adminstyles: SRC + "/scss/admin/index.scss",
        mainstyles: SRC + "/scss/main/index.scss"

    },
    output: {
        path: DIST,
        filename: "[name]-bundle.js"
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
                name: 'commons',
                filename: 'common.js',
                chunks: ['admin', 'main']
            }
        ),
        new ExtractTextPlugin("[name]-bundle.css")
    ],
    module: {
        loaders: [
            {
                test: /.scss$/,
                loader: ExtractTextPlugin.extract("css!sass")
            },
            {test: /.jsx?$/, loader: "babel-loader"}
        ]
    },
    resolve: {
        extensions: ["", ".js", ".jsx"],
        root: [path.join(__dirname, "client", "src", "js", "main")],
        modulesDirectories: ["node_modules"]
    }
}];

Answer

Every entry point gets a JavaScript bundle with the webpack bootstrap code, even if the content is extracted with the extract-text-webpack-plugin. Instead of using a separate entry point for the CSS you should include them in the corresponding entry point, which also makes sense conceptually as the styles are going to be used in them. Each entry also accepts an array.

Your entry should be:

entry: {
    admin: [SRC + "/js/admin/index.js", SRC + "/scss/admin/index.scss"],
    main: [SRC + "/js/main/index.js",  SRC + "/scss/main/index.scss"]
},

If you want to keep the names mainstyles and adminstyles you can also change the extract-text-webpack-plugin to:

new ExtractTextPlugin("[name]styles-bundle.css")

Leave a Reply

Your email address will not be published. Required fields are marked *