In my vite.config.ts
I have a config for CSS modules
在我的vite.config.ts中,我有一个用于CSS模块的配置
return defineConfig({
...
css: {
...
modules: {
localsConvention: "camelCase",
generateScopedName: "[name]__[local]__[hash:base64:2]"
}
},
plugins: [
vue()
]
});
As a result, I get this kind of class names
Output of CSS module class name
结果,我得到了这种类名的输出,即css模块类名
However, it generates an unnecessary string between the component name and the local class name (something like this) -vue-vue-type-style-index-0-lang-module
How can I get rid of it and have a format like ComponentName__class_hash
但是,它会在组件名称和本地类名称之间生成一个不必要的字符串(如下所示)-vue-vue-type-style-index-0-lang-模块如何才能摆脱它并具有类似ComponentName__CLASS_HASH的格式
I tried to use a function for this generateScopedName
property, but I could not set the hash for each class
https://vitejs.dev/config/shared-options.html#css-modules
我试图为这个GenerateScopedName属性使用一个函数,但我无法为每个类https://vitejs.dev/config/shared-options.html#css-modules设置散列
更多回答
优秀答案推荐
To configure the CSS module class name in a Vue project with Vite.js to have a format like ComponentName__class_hash
, you will need to customize the generateScopedName
function in your vite.config.ts
file. You can use the name
and local
variables to construct the class name in your desired format.
要使用Vite.js配置Vue项目中的CSS模块类名称,使其具有类似ComponentName__CLASS_HASH的格式,您需要在vite.config.ts文件中自定义GenerateScopedName函数。您可以使用名称和局部变量以所需的格式构造类名。
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import crypto from 'crypto';
export default defineConfig({
// ... other configurations
css: {
modules: {
localsConvention: 'camelCase',
generateScopedName: (name, filename, css) => {
let componentName = filename
.replace(/\.\w+$/, '')
.split('/')
.pop();
// Generate hash
const hash = crypto
.createHash('md5')
.update(css)
.digest('base64')
.substring(0, 5);
return `${componentName}__${name}__${hash}`;
},
},
},
plugins: [vue()],
});
更多回答
Tested, does not work. Class test
in AboutView.vue
is generated to AboutView.vue?vue&type=style&index=0&lang.module__test__50UU
using this method. Apart from that, the style is not applied anymore when rendered in the browser.
经过测试,不起作用。Vue中的类测试是使用此方法生成到AboutView.vue?vue&type=style&index=0&lang.module__test__50UU的。除此之外,当在浏览器中呈现时,不再应用该样式。
我是一名优秀的程序员,十分优秀!