6

I attempting to follow the tutorial here https://webpack.js.org/guides/asset-management/ however I can never get the css file to load. (the text is never red)

https://github.com/bryandellinger/webpackassetmanagement

> --dist
> ----bundle.js
> ----index.html
> --src
> ----index.js
> ----style.css

webpack.config.js

const path = require('path');
    module.exports = {
      entry: './src/index.js',
      output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
      },
       module: {
         rules: [
           {
             test: /\.css$/,
             use: [
               'style-loader',
               'css-loader'
             ]
           }
         ]
       }
    };

package.json

{
  "name": "webpack1",
  "version": "1.0.0",
  "description": "webpack tutorial",
  "private": true,
  "scripts": {
    "dev": "lite-server",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "css-loader": "^1.0.0",
    "style-loader": "^0.22.1",
    "webpack": "^4.17.1",
    "webpack-cli": "^3.1.0"
  },
  "dependencies": {
    "lite-server": "^2.4.0",
    "lodash": "^4.17.10"
  }
}

index.js

    import _ from 'lodash';

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

        // Lodash, currently included via a script, is required for this line to work
        element.innerHTML = _.join(['Hello', 'webpack'], ' ');
        element.classList.add('hello'); 
        return element;
      }

      document.body.appendChild(component(

));

style.css

.hello {
    color: red;
  }

index.html

<!doctype html>
<html>
  <head>
    <title>Asset Management</title>
  </head>
  <body>
    <script src="bundle.js"></script>
  </body>
</html>
Bryan Dellinger
  • 4,724
  • 7
  • 33
  • 79

2 Answers2

9

You need to import your css file in your main index.js file. You can do this by adding import './style.css';

Updated index.js

import _ from 'lodash';
import './style.css';

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

  // Lodash, currently included via a script, is required for this line to work
  element.innerHTML = _.join(['Hello', 'webpack'], ' ');
  element.classList.add('hello');
  return element;
}

document.body.appendChild(component());
Win
  • 5,498
  • 2
  • 15
  • 20
2

What you forgot to do is import your style.css in your index.js, Webpack doesn't know about your style.css if you don't tell Webpack it's there.

What it will then do is collect all the CSS from the .css files you imported, turn it into a string and pass it to the style-loader which will output it as a <style> in the <head> of your index.html.

Because you haven't imported your style.css in the entrypoint, Webpack doesn't know about it, the css-loader doesn't get to collect the CSS from it and the style-loader doesn't get to output it as a <style>.

Julian
  • 837
  • 1
  • 11
  • 24