jsx/tsx使用cssModule和typescript-plugin-css-modules
1,前言
在vite/webpack搭建的项目中,不管是vue还是react,都可以写jsx/tsx,为了避免样式污染,常用的方式有两种。一种是每个组件都用一个唯一类名class包裹,使用less/scss嵌套样式。另一种是使用cssModule模块化。本文就分享一下如何使用cssModule,并推荐一个好用的插件:typescript-plugin-css-modules,让你在vscode中,能拥有typeScript一样的智能提示。
2,效果图



3,如何使用
注:本文各种配置均使用vscode编辑器。
3.1,安装
- yarn
yarn add -D typescript-plugin-css-modules
- npm
npm install -D typescript-plugin-css-modules
3.2,配置
配置后需要重启vscode,然后项目中使用cssMoudule时,就可以享受到typeScript提示的class类名了,配置如下:
- 配置
tsconfig.json
{
"compilerOptions": {
"plugins": [{"name": "typescript-plugin-css-modules"}]
}
}
- 配置
settings.json
在项目根目录新建.vscode文件夹,在文件夹中新建settings.json,并写入如下配置,用于指明使用typescript.tsdk的位置以及开启提示,如果vscode有提示,记得同意。
{
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true
}
注意:
cssModule可以用于css,less,scss等,使用时,css/less/scss文件后缀必须由.css/.less/.scss变为.module.css/.module.less/.module.scss
4,示例
- index.tsx
import { defineComponent } from 'vue'
import styles from './index.module.scss'
export default defineComponent({
name: 'notFound',
setup() {
return () => (
<div class={styles.main_box}>11111</div >
)
}
})
- index.module.scss
.main_box {
width: 100%;
height: 100%;
position: relative;
overflow: hidden;
text-align: center;
background-color: #ffffff;
}
5,插件错误处理
截止本文发布之时,typescript-plugin-css-modules的版本为3.4.0,此插件有一个bug,会导致cssModule类型提取失败,模块类型是一个{}的情况,如下所示:
Property '
' does not exist on type {}

5.1,错误触发原因
这个bug目前有两个方式都会触发:
-
1,当你项目中使用
less/scss的@include/@mixin等等指令的时候 -
2,当你的项目使用
/ deep /这样的深度选择器语法的时候
5.2,解决办法
- 1,在需要使用
@include/@mixin等等指令的时候,在cssModule文件的头上引入样式,就可以解决(之前是全局引入),如下所示:
@use "../../../static/styles/common.scss" as *;
- 2,换一种深度选择器写法,如下所示:
.main{
& ::deep .el-button{
background-image: linear-gradient(-90deg, #29bdd9 0%, #276ace 100%);
&:hover{
opacity: 0.8;
}
}
}
如果看了觉得有帮助的,我是@上进的鹏多多,欢迎 点赞 关注 评论;END
PS:在本页按F12,在console中输入document.querySelectorAll('.diggit')[0].click(),有惊喜哦
公众号
往期文章
- Vue2全家桶+Element搭建的PC端在线音乐网站
- 超详细的Cookie增删改查
- 助你上手Vue3全家桶之Vue-Router4教程
- 助你上手Vue3全家桶之Vue3教程
- 助你上手Vue3全家桶之VueX4教程
- 使用nvm管理node.js版本以及更换npm淘宝镜像源
- 超详细!Vue-Router手把手教程
- 超详细!Vue的九种通信方式
- 超详细!Vuex手把手教程
个人主页


浙公网安备 33010602011771号