我将 ReactJS 与 Webpack 和 TypeScript 结合使用。 我正在尝试将 CSS 包含在 React 中。但是我的 React 应用程序没有使用我的 CSS。 我创建了一个 global.d.ts 文件来声明我的 css 模块。我将我的 css 导入到 my.tsx 文件中,但是当我将一个类添加到一个元素时,没有任何效果。
我已经尝试安装 css 模块,但没有成功。所以,我刚刚制定了创建 global.d.ts 文件的解决方案
全局.d.ts:
声明模块'*.css';
你好.tsx
import * as css from './Hello.css';
export interface HelloProps {
compiler: string;
framework: string;
}
export class Hello extends React.Component<HelloProps, {}> {
render() {
return (
<form>
<p className={css.test}> Test </p>
</form>
);
}
}
你好.css
.test {
color: red;
}
webpack.config.js
module: {
rules: [
.....
{ test: /\.css$/, exclude: /node_modules/, use: ['style-loader', 'css-loader'] }
]
},
“考”字是黑写的。 什么时候应该是红色
最佳答案
这可能是因为您没有在 css-loader 选项中将模块设置为 true。
// webpack.config.js
rules: [
{
test: /.css$/,
exclude: /node_modules/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
},
},
],
},
],
此外,我会执行以下操作,因为不需要 *
导入。
import css from './Hello.css'
然后在你的 jsx 中:
<Component className={css.test} />
关于ReactJS 中的 jsx 不使用 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54373943/