React18TS项目:配置react-css-modules,使用styleName

他的好处不说了

网上一堆文章一个能打的都没有,

添加开发依赖

复制代码
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;

效果

样式编码

相关推荐
郭邯4 分钟前
用纯前端实现一个代码压缩美化工具,我踩了这三个坑
前端
用户283209679377 分钟前
从进程线程到 async/await:JS Event-loop事件循环机制底层解析
前端·javascript
岁月宁静16 分钟前
一、《从零手撸 Agent》 我用 10 行代码跑通了第一次大模型调用(顺便踩了 4 个坑)
前端·python·agent
计算机魔术师35 分钟前
Fable 5.1 来了,智能体任务成本降 45%——Anthropic 这次为何降价这么狠
前端
Csvn36 分钟前
现代 CSS 新特性深度:container query、:has()、@scope 与 subgrid
前端
梦想的颜色38 分钟前
【AI实战】React‑Native + AI 移动端 APP 完整实战全流程|云端 / 本地大模型、Agent 集成、安装配置、避坑指南
react.js·大模型·app·agent·reactnative·expo·ai 应用开发
计算机魔术师41 分钟前
Anthropic 自己承认:模型越来越难管住了
前端
两只羊ovo1 小时前
Agent 干活的底层地基:path 路径 + fs 文件系统,一次讲透
前端
一用书生1 小时前
我给 ChatGPT、DeepSeek、Kimi 都加了一个「保存为笔记」按钮
前端·ai编程·vibecoding
咖啡无伴侣1 小时前
1. 从零搭建企业级 Monorepo 工程化模板:初始化、应用创建与共享 TypeScript 配置
前端·前端框架