可以在vite-react项目中使用styleName属性的插件
https://www.yarnpkg.cn/package/vite-plugin-react-css-module-stylename
Vite-plugin-react-css-module-styleName
此插件支持 scss 和 less
我们首先需要安装一下scss转换插件
npm install postcss-scss --dev
或
yarn add postcss-scss --dev
如果你使用less,请安装
npm install postcss-less --dev
或
yarn add postcss-less --dev
正式安装插件
npm install vite-plugin-react-css-module-stylename --save--dev
yarn add vite-plugin-react-css-module-stylename --save
因为有元素属性校验的原因,所以我们应该在vite-env.d.ts文件中加入
namespace React {
interface Attributes {
styleName?: string;
}
}
然后我们在vite(vite.config.js/ts)配置文件中添加下面的新增设置
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import reactCssModuleStyleName, { generateScopedName } from 'vite-plugin-react-css-module-styleName';
export default defineConfig(({ mode }) => ({
plugins: [
react(),
reactCssModuleStyleName({ generateScopedName: generateScopedName, env: mode })
],
server: {
open: true
},
css: {
modules: {
generateScopedName: (name: string, filename: string) => {
return generateScopedName(name, filename);
}
}
}
}));
示例
import './index.module.scss';
或
import './index.module.less'
<div styleName="demo">demo</div> // 元素中的使用
如果配置后出现下方错误:
Class extends value undefined is not a constructor or null
请在package.json中加入下方版本,安装后请在尝试一次
"resolutions": {
"postcss": "^8.4.38",
"postcss-scss": "^4.0.9" or "postcss-scss": "^6.0.0"
}