Skip to content

Commit

Permalink
Vite css modules custom class names
Browse files Browse the repository at this point in the history
  • Loading branch information
bgonp committed Apr 9, 2021
1 parent 0f5855b commit bac8863
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
23 changes: 23 additions & 0 deletions src/utils/build.js
Original file line number Diff line number Diff line change
@@ -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)}`
}
11 changes: 3 additions & 8 deletions vite.config.js
Original file line number Diff line number Diff line change
@@ -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: {
Expand Down

0 comments on commit bac8863

Please sign in to comment.