Search code examples
vue.jsvuejs3vitecss-modules

Class name generation isn't working in Vite with Vue


In React projects, I used this config:

css: {
  modules: {
    generateScopedName(name, filename, css) {
      const classNameIndex = css.indexOf(`.${name}`);
      const lineNumber = css.substr(0, classNameIndex).split(/\r?\n/).length;
      const hash = crypto.createHash('sha1').update(css).digest('hex').substring(0, 5);

      const items = filename.split('/');
      return `${items[items.length - 2]}__${name}_${hash}-${lineNumber}`;
    },
  },
}

This was very convenient. You could see which component the class belonged to and which line it was on. But this configuration doesn't work in Vue.

For example, if you take the test class in SomeComponent.vue generated in

SomeComponent.vue?vue&type=style&index=0&lang.module__test__70HHG

using this method. In addition, the style is no longer applied when rendering in the browser.

Is there any solution?


Solution

  • Thanks to @EstusFlask for the suggestion! I tried vite-plugin-pretty-module-classnames, and it works in Vue, but it doesn't show the line number like my React config. Still, it's an improvement.