他的好处不说了
网上一堆文章一个能打的都没有,
添加开发依赖
pnpm add -D @dr.pogodin/babel-plugin-react-css-modules @types/react-css-modules
Babel Plugin "React CSS Modules" | Dr. Pogodin Studio
看@dr.pogodin/babel-plugin-react-css-modules官方文档
不使用babel-plugin-react-css-modules
手搭webpack配置需要处理
1.能启用css modules
对于裸 Webpack,请参见webpack css-loader的 modules 的选项 链接。
2.配置@dr.pogodin/babel-plugin-react-css-modules
使用
- 将此插件作为直接依赖项安装(在不允许编译时 styleName 解析的边缘情况下,插件会回退到运行时解析)。
npm install --save @dr.pogodin/babel-plugin-react-css-modules
- Install Webpack at least as a dev dependency:
至少将 Webpack 作为开发依赖项安装 Webpack:
npm install --save-dev webpack
- Add the plugin to Babel configuration:
将插件添加到 Babel 配置中:
{"plugins": [["@dr.pogodin/react-css-modules", {// The default localIdentName in "css-loader" is "[hash:base64]",// it is highly-recommended to explicitly specify the same value// both here, and in "css-loader" options, including the hash length// (the last digit in the template below)."generateScopedName": "[hash:base64:6]"// See below for all valid options.}]]
}
我自己项目手写的webpack.base.js中使用
const CSS_MODULE_LOCAL_IDENT_NAME = '[name]__[local]___[hash:base64:5]';{test: /.(jsx?)|(tsx?)$/,exclude: /node_modules/,use: [{loader: 'babel-loader',options: {presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript'],plugins: [['@dr.pogodin/react-css-modules',{generateScopedName: CSS_MODULE_LOCAL_IDENT_NAME,autoResolveMultipleImports: true, // 允许多个匿名导入webpackHotModuleReloading: true, // 启用热模块重新加载代码的注入handleMissingStyleName: 'throw', // 确定应为未定义的 CSS 模块执行的操作filetypes: {'.less': {syntax: 'postcss-less',},},},],],},},],
},
{test: /\.less$/,use: ['style-loader',{loader: 'css-loader',options: {modules: {localIdentName: CSS_MODULE_LOCAL_IDENT_NAME,auto: resourcePath => resourcePath.endsWith('.module.less'),},},},{loader: 'postcss-loader',options: {postcssOptions: {plugins: [['postcss-preset-env', {}]],},},},{loader: 'less-loader',options: {lessOptions: {javascriptEnabled: true,},},},],// 排除 node_modules 目录exclude: /node_modules/,
},
3.TS项目不能直接在jsx中使用styleName,会报错,
需要引入@types/react-css-modules
就可以使用module.less和styleName了
项目中使用
index.module.less
.adminColor {color: aquamarine;background-color: black;
}
index.tsx
import React from 'react';
import './index.module.less';const Dashboard: React.FC = () => {return (<><h2 styleName="adminColor">我的</h2><div styleName="adminColor">我的</div></>);
};
export default Dashboard;
效果
样式编码