webpack 样式加载器和 css 加载器不适用于简单示例

webpack style loader and css loader not working for simple example

我试图按照此处的教程进行操作 https://webpack.js.org/guides/asset-management/ 但是我永远无法加载 css 文件。 (文字永远不会变红)

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>

你忘记做的是在你的 index.js 中导入你的 style.css,如果你不告诉 Webpack 它在那里,Webpack 不知道你的 style.css

然后它会做的是从您导入的 .css 文件中收集所有 CSS,将其转换为字符串并将其传递给 style-loader,后者会将其输出为index.html.

<head> 中的 <style>

因为你没有在入口点导入你的 style.css,Webpack 不知道它,css-loader 无法从中收集 CSS 并且style-loader 无法将其输出为 <style>.

您需要在主 index.js 文件中导入 css 文件。您可以通过添加 import './style.css';

已更新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());