-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbabel-source-plugin.cjs
More file actions
72 lines (63 loc) · 2.4 KB
/
babel-source-plugin.cjs
File metadata and controls
72 lines (63 loc) · 2.4 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
const { declare } = require('@babel/helper-plugin-utils');
module.exports = declare((api) => {
api.assertVersion(7);
const { types: t } = api;
return {
name: 'react-source-lens',
visitor: {
JSXOpeningElement(path) {
// Get source info from Babel's source location
const loc = path.node.loc;
if (loc && loc.start) {
// Extract relative path - check multiple directory structures
let sourceFile;
// First, try to extract from src/ directory (traditional React projects)
const srcParts = this.filename.split('/src/');
if (srcParts.length > 1) {
sourceFile = 'src/' + srcParts[srcParts.length - 1];
} else {
// Then, try to extract from app/ directory (Next.js App Router)
const appParts = this.filename.split('/app/');
if (appParts.length > 1) {
sourceFile = 'app/' + appParts[appParts.length - 1];
} else {
// Fallback: try to find a reasonable project root indicator
const pathParts = this.filename.split('/');
// Look for common project root directories and extract from there
const rootIndicators = ['components', 'pages', 'app', 'src'];
let foundRootIndex = -1;
for (let i = pathParts.length - 1; i >= 0; i--) {
if (rootIndicators.includes(pathParts[i])) {
foundRootIndex = i;
break;
}
}
if (foundRootIndex !== -1) {
sourceFile = pathParts.slice(foundRootIndex).join('/');
} else {
// Last resort: just use the filename
sourceFile = this.filename.split('/').pop();
}
}
}
const sourceLine = loc.start.line.toString();
// Add data attributes to the element
const attributes = path.node.attributes;
// Create JSXAttribute nodes for data-source-file and data-source-line
attributes.push(
t.jsxAttribute(
t.jsxIdentifier('data-source-file'),
t.stringLiteral(sourceFile)
)
);
attributes.push(
t.jsxAttribute(
t.jsxIdentifier('data-source-line'),
t.stringLiteral(sourceLine)
)
);
}
}
}
};
});