【问题标题】:Webpack - CSS not appliedWebpack - 未应用 CSS
【发布时间】:2017-07-10 08:52:54
【问题描述】:

我决定尝试一下 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 本身没有拼写错误。我花了很多时间试图弄清楚。我有什么遗漏吗?

【问题讨论】:

    标签: javascript webpack webpack-2


    【解决方案1】:

    您正在将 CSS 加载为仅包含 css-loader 的字符串。您还需要 style-loader 以便在导入时将 CSS 加载到 DOM 中。

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

    【讨论】:

    • 并注意顺序很重要。先放'css-loader'然后放'style-loader'对我不起作用:)
    猜你喜欢
    • 2017-10-04
    • 1970-01-01
    • 2019-01-09
    • 2016-04-09
    • 2020-03-22
    • 2020-03-27
    • 1970-01-01
    • 2017-06-21
    • 2021-11-13
    相关资源
    最近更新 更多