Webpack - CSS未被应用

17

我决定尝试使用Webpack 2。 我正在尝试捆绑js和css。

问题在于页面上的元素未应用CSS(它存在于构建后的文件中)。

这是应用程序结构:

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

Webpack 配置文件:

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!');

运行构建命令时,我得到了以下输出:

[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]

同时,我可以看到CSS已经包含在bundle.js文件中。

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

如果我在HTML中包含CSS文件,它就能正常工作,所以我猜CSS本身没有拼写错误。我花了很多时间尝试找出问题所在。我是否漏掉了什么?

1个回答

26

你正在使用 css-loader 将 CSS 作为字符串加载。为了在导入时将 CSS 加载到 DOM 中,你还需要使用 style-loader

use: [ 'style-loader', 'css-loader' ]

请注意顺序很重要。先使用 'css-loader' 然后再用 'style-loader' 并不能正常运行 :) - perepm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接