CSS模块使用Webpack、Typescript和React格式错误



我一直在尝试通过转换我用纯HTML和CSS构建的网页来学习React。我目前正在使用CSS模块,但注入到<style>标记中的一些CSS似乎有点格式错误:image。奇怪的是,它并没有影响所有的CSS类。

我四处寻找,因为看起来有些CSS没有被应用,这个组件目前看起来是这样的,但应该是这样的。

我的React组件的结构如下:

├── compA
├── index.tsx
└── styles.css
├── compB
├── index.tsx
└── style.css

并且我正在使用:import "./style.css";将CSS文件导入到TSX文件中。我在这里错过了什么?

webpack.config.js:

const TsconfigPathsPlugin = require("tsconfig-paths-webpack-plugin");

module.exports = {
...
entry: {
main: "./src/index.tsx",
},
resolve: {
extensions: [".ts", ".tsx", ".js", ".jsx"],
plugins: [
new TsconfigPathsPlugin({
configFile: path.resolve(__dirname, "./tsconfig.json"),
extensions: [".ts", ".tsx"]
})
],
},
module: {
rules: [
{
test: /.tsx?$/,
loader: "ts-loader"
},
{
test: /.css$/i,
use: [
"style-loader",
{
loader: "css-loader",
options: { modules: true }
}
]
}
],
}
};

这就是CSS模块的行为,因为其目的是让您导入CSS模块,就好像它们是JS:一样

.foo {
background: red;
}
import styles from './foo.css'
export default () => <div className={styles.foo} />

而不是将classNames用作字符串。名称篡改是有意避免冲突的,因为CSS中没有真正的作用域。要保留类名,可以使用:global:

:global(.foo) {
background: red;
}

最新更新