使用Vite js在Vue项目中配置CSS模块类名

问题描述 投票:0回答:1

在我的

vite.config.ts
我有一个CSS模块的配置

return defineConfig({
 ...
  css: {
    ...
    modules: {
      localsConvention: "camelCase",
      generateScopedName: "[name]__[local]__[hash:base64:2]"
    }
  },
  plugins: [
    vue()
  ]
});

结果,我得到了这样的类名
Output of CSS module class name

但是,它会在组件名称和本地类名称之间生成不必要的字符串(类似这样)

-vue-vue-type-style-index-0-lang-module

我怎样才能摆脱它并拥有像
ComponentName__class_hash

这样的格式

我尝试对这个

generateScopedName
属性使用函数,但我无法为每个类设置哈希
https://vitejs.dev/config/shared-options.html#css-modules

css vue.js vuejs3 vite css-modules
1个回答
0
投票

要使用 Vite.js 将 Vue 项目中的 CSS 模块类名称配置为类似

ComponentName__class_hash
的格式,您需要在
generateScopedName
文件中自定义
vite.config.ts
函数。您可以使用
name
local
变量以您所需的格式构造类名称。

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()],
});
© www.soinside.com 2019 - 2024. All rights reserved.