简体   繁体   English

如何设置css模块?

[英]How to set up css-modules?

Official documentation way too complicated and not working for me. 官方文档太复杂了,对我不起作用。 Does anyone know any good article how to set up css-modules with webpack? 有谁知道任何好的文章,如何使用webpack设置css-modules

react-css-modules didn't help either react-css-modules也没有帮助

Update 更新

Here is my modules config. 这是我的模块配置。 It was edited while trying to reach my goal, so it differs from original. 为了达到我的目标而对其进行了编辑,因此与原始版本有所不同。

module: {
    rules: [
        { test: /\.js$/, exclude: /node_modules/, loader: "react-hot-loader!babel-loader" },
        {
            test: /\.scss$/,
            use: [{
                loader: "style-loader"
            }, {
                loader: "css-loader"
            }, {
                loader: "sass-loader"
            }]
        }, {
            test: /\.png$/,
            loader: 'file-loader?name=[name]--[hash].[ext]',
        }
    ],
    loaders: [{
        test: /\.css/,
        loader: 'style-loader!css-loader&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
    }, {
      test: /\.html$/,
      loader: 'file-loader',
    }]
},

It's fairly simple 很简单

You need style-loader, css-loader and set module mode. 您需要样式加载器,css加载器并设置模块模式。

{
  test: /\.css$/,
  loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]' 
}

Like that. 像那样。 Where [name]__[local]___[hash:base64:5] indicates structure of your css classes that webpack will generate for you. 其中[name]__[local]___[hash:base64:5]表示webpack将为您生成的CSS类的结构。

I recommend follow this guide, is really that simple. 我建议遵循此指南,真的很简单。 https://github.com/css-modules/webpack-demo https://github.com/css-modules/webpack-demo

loaders: [{
    test: /\.css$/,
    loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
  }],

after css-loader you need add ? css-loader您需要添加? then modules and so on. 然后是modules ,依此类推。

In the component you need to import style: 在组件中,您需要导入样式:

import style from './App.css';

style - it's just object with properties which match to selectors. 样式-只是具有与选择器匹配的属性的对象。

And usage in component looks so: 组件中的用法如下所示:

const App = props => (   
<header className={style.header}>
   <Link to="/" className={style.link}>Awesome blog</Link>
</header>);

App.css looks so: App.css看起来像这样:

.header {
    font-size: 35px;
    text-align: center;
    line-height: 1.3;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM