在编写代码的时候,经常会出现同名而被覆盖样式的可能,所以添加css Modules可以减少这样的冲突!
首先在webpack的配置文件中的rules加上一下代码,这是新的配置方式
参考:https://github.com/rails/webpacker/issues/2197#issuecomment-517234086
{
test: /\.css$/,
exclude: /node_modules/,
use: ["style-loader", {
loader: "css-loader",
options: {
modules: {
localIdentName: "[local]_[hash:5]",
}
}
}]
},
然后就可以编写样式,并按以下方式引入
/* index.css */
.word {
color: red;
}
import style from "./index.css"
ReactDOM.render(<p className={style.word}>Hello World</p>, document.getElementById("root"))
效果出来了
然后再查看下元素,发现也加上了hash值
然后在ts中同样使用,发现样式确实出来了,但是报错了,不能容忍任何错误
发现是ts的模块机制,所以需要声明模块,创建一个*.d.ts的文件
style为自定义名,随便取
declare module "*.css" {
const style: any;
export default style;
}
这样就不会报错了