[英]How to setup babel-plugin-react-css-modules in create-react-app?
I really like the separation of className and styleName that babel-plugin-react-css-modules offers for global and local styles respectively, but have had some trouble getting the plugin to work with create-react-app. 我真的很喜欢babel-plugin-react-css-modules分别为全局和本地样式提供的className和styleName的分隔,但是让插件与create-react-app一起使用时遇到了一些麻烦。
I've tried installing the plugin by running 我试着通过运行安装插件
npm install babel-plugin-react-css-modules --save npm install babel-plugin-react-css-modules-保存
... as it says to do in the project (github https://github.com/gajus/babel-plugin-react-css-modules#css-modules ) ... ...就像在项目中所说的那样(github https://github.com/gajus/babel-plugin-react-css-modules#css-modules )...
... and have also used craco as suggested in a similar thread (#5113) to help overcome the limitations of create-react-app without the need to eject, but am still unable to import a scss file and reference to it using styleName. ...并且还按照类似线程(#5113)中的建议使用了craco,以帮助克服create-react-app的限制,而无需弹出,但仍然无法导入scss文件并使用styleName对其进行引用。
Does anyone know if I'm missing something else here? 有人知道我是否在这里还缺少其他东西吗? Sorry if it's a noob question, I'm new to React and have been looking for a solution to this for a while now.
抱歉,如果这是一个菜鸟问题,我是React的新手,并且一直在寻找解决方案。
1. add the plugin to .babelrc first. 1.首先将插件添加到.babelrc 。
"plugins": [
["babel-plugin-react-css-modules",
{
"webpackHotModuleReloading": true,
"autoResolveMultipleImports": true
}],....
]
2. add css rule in webpack.config.js . 2.在webpack.config.js中添加CSS规则。
below is my configuration that you can reference from. 以下是您可以参考的我的配置。
make sure that 确保
2.1 option modules set to true. 2.1选项模块设置为true。
2.2 localIdentName follow this format. 2.2 localIdentName遵循这种格式。
localIdentName: "[path]___[name]__[local]___[hash:base64:5]"
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
use: [
{
loader: "babel-loader",
options: { cacheDirectory: true }
}
]
},
{
test: /\.css$/i,
use: [
{
loader: ExtractCssChunks.loader,
options: { hot: true }
},
{
loader: "css-loader", //generating unique classname
options: {
importLoaders: 1, // if specifying more loaders
modules: true,
sourceMap: false,
localIdentName: "[path]___[name]__[local]___[hash:base64:5]" //babel-plugin-css-module format
//localIdentName: "[path][name]__[local]" //recommended settings by cssloader#local-scope , this option generate unique classname for compiled css
}
}
]
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.