【问题标题】:CSS modules with Webpack带有 Webpack 的 CSS 模块
【发布时间】:2019-10-23 07:55:44
【问题描述】:

大家好,我正在尝试在我的简单 webpack 项目中使用 CSS 模块。问题是编译后,webpack 没有将样式类附加到我的 HTML 元素。

我可以在console.log(styles) 中看到一个包含我的编码样式的数组。但是类没有添加到我的 div 中。

有人可以帮我解决这个问题吗?

**package.json**

  "devDependencies": {
    "@babel/core": "^7.6.4",
    "@babel/preset-env": "^7.6.3",
    "babel-loader": "^8.0.6",
    "css-loader": "^3.2.0",
    "path": "^0.12.7",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.9"
  }


**webpack.config.js**

const path = require('path');

module.exports = {
    // Path to your entry point. From this file Webpack will begin his work
    entry: './src/js/app.js',
    output: {
        path: path.resolve(__dirname, 'public/assets'),
        filename: '[name].bundle.js'
    },
    mode: 'development',
    module: {
        rules: [
            {
                test: /\.m?js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env'],
                        plugins: ['@babel/plugin-proposal-object-rest-spread']
                    }
                }
            },
            {
                test: /\.css$/i,
                loader: 'css-loader',
                options: {
                    modules: true,
                },
            },
        ]

    }
};


**src/js/app.js**

import styles from "./css.module.css";
let el = document.getElementById('main');
el.innerHTML=  '<div class="'+styles.red+'">RED OR NOT RED! This is the problem!</div>';

**src/js/css.module.css**

.red{ color: red; }

**public/index.html**

<div id="main"></div>
<script src="assets/main.bundle.js"></script>

【问题讨论】:

  • 你的控制台输出是什么?
  • 红色或非红色!这就是问题所在!

标签: css webpack css-modules


【解决方案1】:

你需要使用style-loader 将你的css注入到dom中。

{
  test: /\.css$/,
  use: [
    'style-loader',
    {
      loader: 'css-loader',
      options: {
        modules: true
      }
    }
  ]
}

【讨论】:

  • 嗨,Arseny,谢谢,这是工作,但必须注入 dom?想象一下我的页面中有很多组件,比如按钮、箭头等......都在 dom 中?
  • 不,这不是强制性的,实际上最好在创建生产构建时将 css 提取到单独的文件中。为此,您需要使用MiniCssExtractPlugin
猜你喜欢
  • 2019-05-11
  • 1970-01-01
  • 2020-07-24
  • 1970-01-01
  • 2018-01-06
  • 2018-11-05
  • 2019-03-09
  • 2017-03-26
  • 2014-06-15
相关资源
最近更新 更多