在React与CSS-loader和Webpack中使用字符串类名称

时间:2018-08-16 10:12:37

标签: css reactjs webpack css-loader

我正在关注一些教程,这些教程是关于如何在Webpack中为React设置内部sass / scss / css支持的。终于有了令我满意的东西,使用HtmlWebpackPlugin根据模板index.htmlsass-loadertypings-for-css-modules-loader包装器来生成css-loader在打字稿中使用css模块)和MiniCssExtractPlugin,以便在我建立的dist文件夹中创建单独的css文件。我的配置如下:

module: {
  rules: [

    ...

    { test: /\.(sa|sc|c)ss?$/,
      use: [
        {
          loader: MiniCssExtractPlugin.loader,
          options: {}
        },
        {
          loader: 'typings-for-css-modules-loader',
          options: {
            modules: true,
            namedExport: true,
            camelCase: true
          }
        },
        'sass-loader'
      ]
    }
  ]
}

当我将React组件中的CSS类作为对象导入时,此设置有效:

hello.css

.foo {
    color: #5df7ff;
}

hello.tsx

import * as React from 'react';

import { foo } from './hello.css';

export interface HelloProps {
  compiler: string;
  framework: string;
}

export const Hello = (props: HelloProps) =>
  <h1 className={foo}>Hello: {props.compiler} and {props.framework}!!!</h1>; // This works: text is colored correctly

当我想在React组件中使用字符串类名称时,就会出现问题(与以前的css一样):

hello.tsx

import * as React from 'react';

import './hello.css';

export interface HelloProps {
  compiler: string;
  framework: string;
}

export const Hello = (props: HelloProps) =>
  <h1 className="foo">Hello: {props.compiler} and {props.framework}!!!</h1>; // This does not work: text is not colored

我认为这是因为Webpack加载器不够“智能”,无法正确解析React DOM中的字符串类名称:这些加载器没有将字符串类名称映射到css-loader生成的哈希名称。 / p>

我知道在React中使用字符串css类名不是包含css类的惯用方式:理想情况下,每个组件使用css模块将有一个完整的css类,就像在第一个示例中那样,它会被导入。

但是,当使用外部UI组件库(例如Ant Design,Semantic UI)时,似乎会引用它们自己的CSS字符串类。

这使我无法使用这些外部库。

使用antd(蚂蚁设计)的示例:

anthello.tsx

import React from 'react';
import Button from 'antd/lib/button';
import 'antd/es/button/style/index.css';

export interface HelloAntProps {
  message: string;
}

export const HelloAnt = ({ message }: HelloAntProps ) => {
  return (
    <div>
      <h1>Hello {message}</h1>
      <Button type="primary">Test</Button>
    </div>
  );
};

使用加载程序堆栈生成的css文件:

._3WAJv754FZTMKDXGocE913 { /* This class corresponds to the Ant Design ant-btn class */
  line-height: 1.5;
  display: inline-block;
  font-weight: 400;
  text-align: center;
  ...

和在实际DOM中寻找的css类:

<button type="button" class="ant-btn ant-btn-primary"><span>Test</span></button> 
<!-- This does not work, as the only classes present in the css are the hashed ones generated by css-loader -->

我不知道其他如何导入这些库,并使用Webpack将它们打包到单个CSS捆绑包中,而又无法正常工作。

我想念什么吗?

tl; dr

有什么方法可以通过Webpack加载器在React DOM中使用css-loader来正确解析CSS类字符串吗?我有什么解决方法吗?

1 个答案:

答案 0 :(得分:1)

更新:通过禁用我的css-loader中的'css-modules'选项,设法解决了该问题。

css类名称的哈希值归因于css-modules选项。通过禁用此选项,不再对类名进行哈希处理,从而使外部库可以直接引用其自身的类。

通过保留css-modules选项似乎无法轻松解决问题。