-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathimport-inject.ts
More file actions
177 lines (150 loc) · 5.06 KB
/
Copy pathimport-inject.ts
File metadata and controls
177 lines (150 loc) · 5.06 KB
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
174
175
176
177
import fs from 'fs-extra';
import path from 'path';
import { glob } from 'glob';
import { fileExists, createImportStatement } from './utils';
interface TrackedImport {
sourceFile: string;
cssPaths: string[];
}
/**
* Resolve a CSS import path to an absolute path
*/
const resolveCssPath = (
cssImportPath: string,
sourceFile: string,
srcDir: string
): string | null => {
if (cssImportPath.startsWith('@/')) {
return path.join(srcDir, cssImportPath.slice(2));
}
if (cssImportPath.startsWith('./') || cssImportPath.startsWith('../')) {
return path.resolve(path.dirname(sourceFile), cssImportPath);
}
return null;
};
/**
* Calculate the import path from a JS file to a CSS file
*/
const calculateImportPath = (
jsFile: string,
cssFile: string,
srcDir: string,
distDir: string
): string | null => {
const cssRelativeToSrc = path.relative(srcDir, cssFile);
const cssOutputPath = path.join(distDir, cssRelativeToSrc);
const cssRelativeToJs = path.relative(path.dirname(jsFile), cssOutputPath);
const normalized = cssRelativeToJs.replace(/\\/g, '/');
return normalized.startsWith('.') ? normalized : `./${normalized}`;
};
/**
* Copy CSS file to dist and get the import path
*/
const copyAndResolveCss = async (
cssImportPath: string,
sourceFile: string,
srcDir: string,
distDir: string,
jsOutputFile: string
): Promise<string | null> => {
const cssSourcePath = resolveCssPath(cssImportPath, sourceFile, srcDir);
if (!cssSourcePath || !(await fileExists(cssSourcePath))) {return null;}
const cssRelativeToSrc = path.relative(srcDir, cssSourcePath);
const cssOutputPath = path.join(distDir, cssRelativeToSrc);
// Copy CSS file if not already there
if (!(await fileExists(cssOutputPath))) {
await fs.ensureDir(path.dirname(cssOutputPath));
await fs.copy(cssSourcePath, cssOutputPath);
}
return calculateImportPath(jsOutputFile, cssSourcePath, srcDir, distDir);
};
/**
* Remove all empty css comments from content
*/
const removeEmptyCssComments = (content: string): string => {
return content.replace(/\/\*\s*empty css\s*\*\//g, '');
};
/**
* Insert code at the top of a file, after use client directive if present
*/
const insertAtTop = (content: string, codeToInsert: string): string => {
let insertPos = 0;
const useClientMatch = content.match(/^(['"]use client['"];?)/);
if (useClientMatch) {
insertPos = useClientMatch[0].length;
if (content[insertPos] !== '\n') {
insertPos = content.indexOf('\n', insertPos) + 1;
} else {
insertPos++;
}
}
return content.slice(0, insertPos) + codeToInsert + content.slice(insertPos);
};
/**
* Inject CSS imports into component files (e.g., Button/index.js gets import "./Button.css")
*
* NOTE: This function assumes the CSS filename matches the parent directory name.
* For example, components/Button/index.js expects components/Button/Button.css to exist.
* Components that don't follow this naming convention will be silently skipped.
*/
export const injectComponentCss = async (
distDir: string,
format: 'esm' | 'cjs',
ext: string
): Promise<void> => {
const files = await glob(`**/index.${ext}`, { cwd: distDir, absolute: true });
for (const jsFile of files) {
const dir = path.dirname(jsFile);
const component = path.basename(dir);
const cssFile = path.join(dir, `${component}.css`);
if (!(await fileExists(cssFile))) {continue;}
const content = await fs.readFile(jsFile, 'utf-8');
if (content.includes(`${component}.css`)) {continue;}
const importStmt = createImportStatement(`./${component}.css`, format) + '\n';
const updated = insertAtTop(content, importStmt);
await fs.writeFile(jsFile, updated);
}
};
/**
* Inject CSS imports into files that had CSS imports in source
* (e.g., ThemeProvider.tsx imports theme CSS files)
*/
export const injectRegularCssImports = async (
trackedImports: TrackedImport[],
rootDir: string,
distDir: string,
format: 'esm' | 'cjs'
): Promise<void> => {
if (trackedImports.length === 0) {return;}
const srcDir = path.join(rootDir, 'src');
for (const { sourceFile, cssPaths } of trackedImports) {
const relativeToSrc = path.relative(srcDir, sourceFile);
const jsOutputFile = path.join(
distDir,
relativeToSrc.replace(/\.tsx?$/, `.${format === 'esm' ? 'js' : 'cjs'}`)
);
if (!(await fileExists(jsOutputFile))) {continue;}
let content = await fs.readFile(jsOutputFile, 'utf-8');
// Build import statements
const importStatements: string[] = [];
for (const cssPath of cssPaths) {
const importPath = await copyAndResolveCss(
cssPath,
sourceFile,
srcDir,
distDir,
jsOutputFile
);
if (importPath) {
importStatements.push(createImportStatement(importPath, format));
}
}
// Remove empty css comments and inject imports
content = removeEmptyCssComments(content);
if (importStatements.length > 0) {
const importCode = importStatements.join('\n') + '\n';
content = insertAtTop(content, importCode);
}
await fs.writeFile(jsOutputFile, content);
}
};