Skip to content

Commit 12ca0ea

Browse files
committed
Increase dictionary
Closes #6
1 parent 32b5ffc commit 12ca0ea

File tree

3 files changed

+55
-31
lines changed

3 files changed

+55
-31
lines changed

src/counter.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
const DEFAULT_DICTIONARY = '_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
2+
3+
export const counter = (dictionary: string = DEFAULT_DICTIONARY) => {
4+
const sequence: string[] = [dictionary[0]];
5+
6+
return () => {
7+
const str = sequence.join('');
8+
let carry = 0;
9+
10+
for (let i = 0; i < sequence.length; i++) {
11+
const index = dictionary.indexOf(sequence[i]) + carry + 1;
12+
13+
if (index < dictionary.length) {
14+
sequence[i] = dictionary[index];
15+
16+
17+
/**
18+
* Make sure the following rules are not violated:
19+
* 1. The first character cannot be a number
20+
* 2. The second character cannot be a number if the first is a dash
21+
* 3. The dash cannot be the only character
22+
*
23+
* https://www.w3.org/TR/CSS21/syndata.html#characters
24+
*/
25+
const [c1, c2] = sequence;
26+
if (
27+
(c1 >= '0' && c1 <= '9') ||
28+
(c1 === '-' && (c2 >= '0' && c2 <= '9')) ||
29+
(c1 === '-' && sequence.length === 1)
30+
) {
31+
i--;
32+
continue;
33+
}
34+
35+
carry = 0;
36+
break;
37+
} else {
38+
sequence[i] = dictionary[0];
39+
carry = 1;
40+
}
41+
}
42+
43+
if (carry) {
44+
sequence.push(dictionary[0]);
45+
}
46+
47+
return str;
48+
};
49+
};

src/createCounter.ts

Lines changed: 0 additions & 26 deletions
This file was deleted.

src/index.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,30 @@
11
import {Plugin, UserConfig} from 'vite';
2-
import {createCounter} from './createCounter';
2+
import {counter} from './counter';
33

44
export interface OptimizeCssModuleOptions {
55
dictionary?: string;
6+
apply?: 'build' | 'serve';
67
}
78

89
export const optimizeCssModules = (options?: OptimizeCssModuleOptions): Plugin => {
9-
const next = createCounter(options?.dictionary);
10+
const next = counter(options?.dictionary);
1011
const map: Map<string, string> = new Map();
1112

1213
return {
1314
name: 'optimize-css-modules',
14-
apply: 'build',
15+
apply: options?.apply ?? 'build',
1516
config: (): UserConfig => ({
1617
css: {
1718
modules: {
1819
generateScopedName: (name: string, fileName: string) => {
19-
const key = `${fileName} ${name}`;
20+
const key = fileName + name;
2021

2122
let hash = map.get(key);
2223
if (!hash) {
2324
map.set(key, (hash = next()));
2425
}
2526

26-
return hash;
27+
return hash!;
2728
}
2829
}
2930
}

0 commit comments

Comments
 (0)