From bac8863e4695f052c8a7ab4ff32a5403f614e15f Mon Sep 17 00:00:00 2001 From: Borja Gonzalez Date: Fri, 9 Apr 2021 17:16:07 +0200 Subject: [PATCH] Vite css modules custom class names --- src/utils/build.js | 23 +++++++++++++++++++++++ vite.config.js | 11 +++-------- 2 files changed, 26 insertions(+), 8 deletions(-) create mode 100644 src/utils/build.js diff --git a/src/utils/build.js b/src/utils/build.js new file mode 100644 index 0000000..1b62d5f --- /dev/null +++ b/src/utils/build.js @@ -0,0 +1,23 @@ +import path from 'path' + +const getFileName = (filename) => path.basename(filename, '.module.css') + +const hash = (content) => content + .split('') + .reduce( + (acc, letter) => Math.imul(31, acc) + letter.charCodeAt(0) | 0, + Math.ceil(Math.random() * 1000) + ) + .toString(36) + .substr(-5) + +export const generateScopedName = () => { + const hashes = {} + const getHash = (name, content) => { + if (!hashes[name]) hashes[name] = hash(content) + return hashes[name] + } + + return (name, filename, css) => + `${getFileName(filename)}__${name}--${getHash(name, css)}` +} diff --git a/vite.config.js b/vite.config.js index c742162..13d18ed 100644 --- a/vite.config.js +++ b/vite.config.js @@ -1,18 +1,13 @@ +import path from 'path' import { defineConfig } from 'vite' import reactRefresh from '@vitejs/plugin-react-refresh' -const path = require('path') +import { generateScopedName } from './src/utils/build' export default defineConfig({ css: { modules: { - generateScopedName: function (name, filename) { - const path = require('path') - const file = path.basename(filename, '.module.css') - const hash = Math.random().toString(36).slice(2, 8) - - return `${file}__${name}--${hash}` - }, + generateScopedName: generateScopedName(), }, }, esbuild: {