CSS模块组合不起作用

时间:2018-01-17 06:24:37

标签: css reactjs webpack postcss css-modules

我尝试使用postcss + cssnext设置css模块。这一切似乎都运行正常,但composes关键字根本不起作用。编译包时规则就消失了。

这是我的webpack配置文件:

'use strict'

const path = require('path')
const webpack = require('webpack')
const HtmlPlugin = require('html-webpack-plugin')

module.exports = {
    devtool: 'inline-source-map',
    entry: [
        'react-hot-loader/patch',
        'webpack-dev-server/client?http://localhost:3000',
        'webpack/hot/only-dev-server',
        path.join(__dirname, 'src', 'index')
    ],
    output: {
        path: path.join(__dirname, 'dist'),
        filename: '[name]-[hash].js',
        publicPath: ''
    },
    plugins: [
        // new DashboardPlugin(),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NamedModulesPlugin(),
        new HtmlPlugin({
            title: 'Github App',
            template: path.join(__dirname, 'src', 'html', 'template-dev.html')
        })
    ],
    module: {
        rules: [{
            test: /\.js$/,
            exclude: /node_modules/,
            include: /src/,
            use: 'babel-loader'
        }, {
            test: /\.css$/,
            exclude: /node_modules/,
            include: /src/,
            use: ['style-loader', {
                loader: 'css-loader',
                options: {
                    modules: true,
                    importLoaders: 1,
                    localIdentName: '[local]--[hash:base64:5]'
                }
            }, {
                loader: 'postcss-loader',
                options: {
                    ident: 'postcss'
                }
            }]
        }]
    },
    resolve: {
        alias: {
            Src: path.join(__dirname, 'src'),
            Components: path.join(__dirname, 'src', 'components')
        }
    }
}

我在这个开发环境中使用了样式加载器,因此我可以使用热重新加载。正在导入css文件,如下所示:import './app.css' app.css:

:global{
    .app {
        float: left;
        padding: 10px;
        width: 100%;
    }
}

.className {
    color: green;
    background: red;
}

.otherClassName{
    composes: className;
    color: yellow;
}

这导致:

enter image description here

我的postcss.config.js文件:

module.exports = {
    plugins: {
        'postcss-import': {},
        'postcss-cssnext': {
            browsers: ['last 2 versions', '> 5%']
        },
        'postcss-nested': {}
    }
}

我错过了让composes工作的东西吗?

1 个答案:

答案 0 :(得分:0)

看起来很好: webpack的css_loader的实现是在导出样式时添加两个类(参见https://github.com/webpack-contrib/css-loader#composing

这也更有意义,因为它最终会渲染出更少的CSS代码。 尝试导入样式并将它们应用到HTML节点,您将看到它应该接收这两个类。

在你的例子中,它会做类似的事情:

exports.locals = {
  className: 'className-2yqlI',
  otherClassName: 'className-2yqlI otherClassName-1qAvb'
}

所以当你这样做时:

import styles from '../app.css'

// ...

<div className={styles.otherClassName} />

div获得两个类。