首页 文章

CSS模块组合不起作用

提问于
浏览
2

我正在尝试使用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

    看起来很好: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获得两个类 .

相关问题