webpackwebpack-2webpack-style-loadercss-loader

webpack not generating css file


Implementing webpack asset management tutorial .but webpack is not generating css file in output path

webpack.config.js

const config = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: __dirname + '/build'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      },
      {
        test: /\.(jpeg)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[path][name].[ext]'
            }
          }
        ]
      }
    ]
  }
};

index.js

  import './style.css';
  import Icon from './yo1.jpg';

  function component() {
    var element = document.createElement('div');

    element.innerHTML = 'hello webpack'
    element.classList.add('hello');

    var myIcon = new Image();
    myIcon.src = Icon;

    element.appendChild(myIcon);

    return element;
  }

  document.body.appendChild(component());

enter image description here

Problem

images are nicely created in build folder

but

it does not creates style.css in build folder , what wrong i am doing ?


Solution

  • webpack does not create separate css files. It get's bundled with the javascript and is injected into the DOM as style tags by webpack bootstrap code.

    If you want to create separate css file, you can use the ExtractTextPlugin - https://github.com/webpack-contrib/extract-text-webpack-plugin

    const ExtractTextPlugin = require("extract-text-webpack-plugin");
    
    module.exports = {
      module: {
        rules: [
          {
            test: /\.css$/,
            use: ExtractTextPlugin.extract({
              fallback: "style-loader",
              use: "css-loader"
            })
          }
        ]
      },
      plugins: [
        new ExtractTextPlugin("styles.css"),
      ]
    }