Search code examples
javascriptcsswebpackwebpack-style-loader

Webpack 1.12: Bundle css files


I'm successfully bundling .js files and processing them correctly with the loaders. My current config is here:

"use strict";

var webpack = require("webpack");

module.exports = {
    entry: {
        main: 'main.js',
        vendor: ["fixed-data-table","react","react-dom","jquery", "bootstrap"],
    },
    output: { path: "../resources/public", filename: 'bundle.js' },

    plugins: [
        new webpack.optimize.CommonsChunkPlugin(/* chunkName= */"vendor", /* filename= */"static/vendor.bundle.js"),
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery"
        }),
    ],

    module: {
        loaders: [
            {
                test: /.js?$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['es2015', 'react', 'stage-0']
                }
            }
        ]
    },
};

I now have a bunch of css files, some of them from the vendor modules as well. How do I bundle them in the same manner to a bundle.css for my own(there's just one) and vendor.bundle.css for the modules, similar to the structure above?


Solution

  • I believe the extract-text-webpack-plugin is exactly what you want for achieving this. More info here. I use it on all my webpack builds and rather simple to implement. You will also need to use style-loader/css-loader along with the extract text plugin. Once you do all that your webpack config should look something like this. var webpack = require("webpack");

    module.exports = {
      entry: {
            main: 'main.js',
            vendor: ["fixed-data-table","react","react-dom","jquery", "bootstrap"],
        },
        output: { path: "../resources/public", filename: 'bundle.js' },
    
        plugins: [
            new webpack.optimize.CommonsChunkPlugin(/* chunkName= */"vendor", /* filename= */"static/vendor.bundle.js"),
            new ExtractTextPlugin("[name].css"),
            new webpack.ProvidePlugin({
                $: "jquery",
                jQuery: "jquery"
            }),
        ],
    
        module: {
            loaders: [
                {
                  test: /.js?$/,
                  loader: 'babel-loader',
                  exclude: /node_modules/,
                  query: {
                    presets: ['es2015', 'react', 'stage-0']
                  }
                },
                {
                  test: /\.css$/,
                  loader: ExtractTextPlugin.extract("style-loader","css-loader"),
                },
            ]
        },
    };
    

    From there just require your css file within your main.js file.

    require('./path/to/style.css');
    

    Now when you run webpack it should output a css file within your root directory.