Webpack样式加载器和CSS加载器不适用于简单示例

时间:2018-08-26 11:57:00

标签: javascript webpack webpack-style-loader css-loader

我尝试按照此处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>

2 个答案:

答案 0 :(得分:1)

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

然后将执行的操作是从导入的.css文件中收集所有CSS,将其转换为字符串并将其传递给style-loader,后者将其输出为<style>在您的<head>的{​​{1}}中。

因为您尚未在入口点导入index.html,所以Webpack对此一无所知,style.css无法从中收集CSS,而css-loader不能将其输出为style-loader

答案 1 :(得分:1)

您需要在主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());