-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvite.config.plugin.js
89 lines (76 loc) · 2.52 KB
/
vite.config.plugin.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
/**
* Babel plugin that adds file paths as data attributes to JSX elements.
* @param {object} api - Babel API object.
* @returns {object} - Babel visitor object.
*/
export default function ({ types: t }) {
return {
visitor: {
/**
* Visits JSXOpeningElement nodes.
* @param {object} path - Babel path object.
* @param {object} state - Babel state object.
*/
JSXOpeningElement(path, state) {
const { node } = path
// Ignore the Fragment element.
if (
(t.isJSXIdentifier(node.name) &&
node.name &&
(node.name.name === 'React.Fragment' ||
node.name.name === 'Fragment')) ||
t.isJSXFragment(node)
) {
return
}
// Get the full path of the file.
const fullPath = state.file.opts.filename
// Remove everything up to 'src' in the path.
let parts = fullPath.split('/')
while (parts.length && parts[0] !== 'src') {
parts.shift()
}
parts.shift()
// Keep only the last 3 parts of the path.
parts = parts.slice(-3)
let file = parts.join('/')
// Remove the file extension.
parts = file.split('.')
parts.pop()
file = parts.join('.')
// Get the line number.
const lineNumber = path.node.loc.start.line
// Add the file path as a data attribute.
const jsxAttribute = t.jsxAttribute(
t.jsxIdentifier('x-jsx'),
t.stringLiteral(`${file}:${lineNumber}`)
)
// Find x-jsx attribute
let xJsxIndex = path.node.attributes.findIndex(
attr => attr?.name && attr?.name?.name === 'x-jsx'
)
// If x-jsx exists, don't add it again
if (xJsxIndex !== -1) {
return
}
// Find x-id attribute
let xIdIndex = path.node.attributes.findIndex(
attr => attr?.name && attr?.name?.name === 'x-id'
)
let xIdAttribute
// If x-id exists, remove it from its current position
if (xIdIndex !== -1) {
xIdAttribute = path.node.attributes[xIdIndex]
path.node.attributes.splice(xIdIndex, 1)
}
if (!xIdAttribute) {
// Add x-jsx at the beginning of the attributes array
path.node.attributes.unshift(jsxAttribute)
} else {
// Add x-id and x-jsx at the beginning of the attributes array
path.node.attributes.unshift(xIdAttribute, jsxAttribute)
}
},
},
}
}