-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddTailwindPrefix.js
173 lines (152 loc) · 5.05 KB
/
addTailwindPrefix.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import fse from 'fs-extra';
import { resolve, join } from 'path';
import tailwindConfig from '../tailwind.config.js';
const { readdir, stat: _stat, readFile, writeFile } = fse;
const firstRegex = /className=["'{][cn({`]*([\s\S]*?)[`'})]+["'}]/gm;
// Use backticks ` for any string that is not a class inside className
const secondRegex = /['"]([^'"]+)['"]/gm;
function getTailwindPrefix() {
return tailwindConfig?.prefix ?? '';
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function replaceLast(str, pattern, replacement) {
const match =
typeof pattern === 'string'
? pattern
: (str.match(new RegExp(pattern.source, 'g')) || []).slice(-1)[0];
if (!match) return str;
const last = str.lastIndexOf(match);
return last !== -1
? `${str.slice(0, last)}${replacement}${str.slice(last + match.length)}`
: str;
}
/**
* Function to add the Tailwind prefix to a CSS class
* @param str
* @param newPrefix
* @param oldPrefix
* @returns
*/
function replacement(str, newPrefix, oldPrefix) {
// If the old prefix is present, replace it with the new one
if (
oldPrefix &&
(str.startsWith(oldPrefix) ||
str.startsWith(`-${oldPrefix}`) ||
str.startsWith(`!${oldPrefix}`) ||
str.includes(`:${oldPrefix}`))
) {
return str.replace(oldPrefix, newPrefix);
}
// Otherwise, add the new prefix only if it's not already applied
if (str.includes(':')) {
return !str.includes(`:${newPrefix}`)
? replaceLast(str, ':', `:${newPrefix}`)
: str;
}
if (str.includes('!')) {
return !str.includes(`!${newPrefix}`)
? str.replace('!', `!${newPrefix}`)
: str;
}
if (str.startsWith('-')) {
return !str.startsWith(`-${newPrefix}`)
? str.replace('-', `-${newPrefix}`)
: str;
}
return !str.startsWith(newPrefix) ? `${newPrefix}${str}` : str;
}
/**
* Function to modify CSS classes in a file
* @param content - file content
* @param newPrefix - prefix to add
* @param oldPrefix - prefix to replace
* @returns
*/
function updateTailwindClasses(content, newPrefix, oldPrefix) {
let newContent = content;
let classNameValues = [];
let distinctClassNames = new Map();
// Retrieve the CSS classes defined in the "className" attributes
const classNameAttributes = newContent.match(firstRegex) ?? [];
classNameAttributes.map((match) => {
classNameValues = [
...classNameValues,
...(match.match(secondRegex) ?? []),
];
});
// Keep only the unique class values
classNameValues.map((classNameValue) =>
classNameValue
.replaceAll("'", '')
.split(' ')
.map((className) => {
if (!distinctClassNames.has(className)) {
distinctClassNames.set(className, className);
}
})
);
// Modify the file content
[...distinctClassNames.values()].forEach((className) => {
// This RegExp avoids adding the prefix twice in the same place
const regExp = new RegExp(
`(?<=[' ])${escapeRegExp(className)}(?=[' ])`,
'g'
);
newContent = newContent.replaceAll(regExp, (match) =>
replacement(match, newPrefix, oldPrefix)
);
});
return newContent;
}
/**
* Function to process all .ts and .tsx files in a "dir" folder
* @param dir - folder to process
* @param newPrefix - prefix to add
* @param oldPrefix - prefix to replace
*/
async function processFiles(dir, newPrefix, oldPrefix) {
const files = await readdir(dir);
for (const file of files) {
const filePath = join(dir, file);
const stat = await _stat(filePath);
if (stat.isDirectory()) {
// If it's a directory, recursively call this function
await processFiles(filePath, newPrefix, oldPrefix);
} else if (file.endsWith('.ts') || file.endsWith('.tsx')) {
// If it's a .ts or .tsx file, modify it
let content = await readFile(filePath, 'utf8');
const updatedContent = updateTailwindClasses(
content,
newPrefix,
oldPrefix
);
if (content !== updatedContent) {
await writeFile(filePath, updatedContent, 'utf8');
console.log(`Prefix updated in: ${filePath}`);
}
}
}
}
/**
* @argv 2 : old prefix to replace
*/
async function main() {
const newPrefix = getTailwindPrefix();
const oldPrefix = process.argv[2];
if (!newPrefix && !oldPrefix) {
console.log('No prefix to add or replace.');
return;
}
if (oldPrefix) {
console.log(`Old prefix: "${oldPrefix}"`);
}
console.log(`New prefix: "${newPrefix}"`);
const srcDir = resolve('./src');
await processFiles(srcDir, newPrefix, oldPrefix);
}
main().catch((error) => {
console.error("Error during script execution:", error);
});