我正在学习一些关于如何在 Webpack 中为 React 设置内部 sass/scss/css 支持的教程。我终于得到了我满意的东西,使用 HtmlWebpackPlugin
生成基于模板的 index.html
,sass-loader
,typings-for-css-modules-loader
(用于处理 typescript 中的 css 模块的 css-loader
包装器)和 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 类作为对象导入时,此设置有效:
你好.css
.foo {
color: #5df7ff;
}
你好.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 相同):
你好.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 生成的散列类名。
我知道在 React 中使用字符串 css 类名并不是包含 css 类的惯用方式:理想情况下,每个组件都有一个完整的 css 类,使用您将在第一个示例中导入的 css 模块。
然而,当使用外部 UI 组件库(例如 Ant Design、Semantic UI)时,问题就出现了,这些组件库似乎引用了它们自己的 css 字符串类。
这让我无法使用这些外部库。
使用 antd
(Ant Design) 的例子:
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 类字符串?我是否缺少任何解决方法?
最佳答案
更新:通过在我的 css-loader
中禁用“css-modules”选项设法解决了这个问题。
css 类名的散列是由于 css-modules
选项。通过禁用此选项,类名称不再被散列,使外部库能够直接引用它们自己的类。
看起来问题并不能通过保留 css-modules
选项轻松解决。
关于css - 在带有 css-loader 和 Webpack 的 React 中使用字符串类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51874593/