Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webpack style loader and css loader not working for simple example

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>
like image 478
Bryan Dellinger Avatar asked Jan 02 '23 23:01

Bryan Dellinger


1 Answers

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());
like image 163
Win Avatar answered Jan 04 '23 13:01

Win