17

I have decided to give it a try to Webpack 2. I'm trying to bundle js and css.

The problem is that CSS in not being applied the elements on the page (it is present in the built file).

This is the app structure:

app
  |-styles.css
  |-app.js
build
  |-bundle.js
index.html

webpack config file:

var path = require('path');

module.exports = {
    entry: './app/app.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'build')
    },
    module: {
       rules: [
          {
            test: /\.css$/, 
            use: 'css-loader'
          }
      ]
   }
}

index.html:

<html>
<head>
   <script src="./build/bundle.js"></script>
</head>
<body>
    <div class="abc"> hello </div>
</body>

app.js:

require('./styles.css');
console.log('js loaded!');

When I run build command getting this output:

[0] ./app/styles.css 240 bytes {0} [built] [1] ./~/css-loader/lib/css-base.js 1.51 kB {0} [built] [2] ./app/app.js 148 bytes {0} [built]

Also I can see the css is included in the bundle.js file

exports.push([module.i, ".abc {\r\n    width: 300px;\r\n    height: 100px;\r\n    background-color: red;\r\n}", ""]);

If I include css file in html it works fine so I guess there is no spelling mistake in CSS itself. I spent quite a lot of time trying to figure it out. Is there anything I'm missing?

1 Answer 1

26

You're loading the CSS as a string with just css-loader. You'll need style-loader as well in order to have the CSS load into the DOM when you import it.

use: [ 'style-loader', 'css-loader' ]
Sign up to request clarification or add additional context in comments.

1 Comment

And note that the order is important. Putting 'css-loader' first and then 'style-loader' isn't working for me :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.