Skip to content

Commit

Permalink
feat: enhance CSS module naming with scoped hash based on component type
Browse files Browse the repository at this point in the history
  • Loading branch information
Perdolique committed Nov 10, 2024
1 parent ea2517e commit fc44a51
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions nuxt.config.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,26 @@
import { createHash, type BinaryLike } from 'crypto'
import { basename } from 'path'

type ComponentType = 'page' | 'layout' | 'component';

function getComponentType(filePath: string) : ComponentType {
if (filePath.includes('/app/pages/')) {
return 'page';
} else if (filePath.includes('/app/layouts/')) {
return 'layout';
} else {
return 'component';
}
}

function getComponentName(componentName: string, componentType: ComponentType) : string {
if (componentType === 'component') {
return componentName;
}

return `${componentType}-${componentName}`;
}

// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
modules: [
Expand Down Expand Up @@ -58,6 +81,25 @@ export default defineNuxtConfig({

vite: {
css: {
modules: {
generateScopedName(className: string, filename: string, data: BinaryLike) : string {
const hash = createHash('sha256')
.update(data)
.digest('hex')
.slice(0, 6);

const filePath = filename
.replace(/\.vue\?.+?$/u, '')
.replace(/\[|\]/gu, '');

const baseName = basename(filePath);
const componentType = getComponentType(filePath);
const componentName = getComponentName(baseName, componentType);

return `${componentName}_${className}_${hash}`;
}
},

preprocessorOptions: {
scss: {
api: 'modern-compiler',
Expand Down

0 comments on commit fc44a51

Please sign in to comment.