-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite.js
More file actions
92 lines (77 loc) · 2.91 KB
/
vite.js
File metadata and controls
92 lines (77 loc) · 2.91 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
const { parse } = require('acorn')
const OptionsParser = require('./lib/options-parser')
const { detectReactComponents, generateDisplayNameCode } = require('./lib/component-detector')
const VALID_FILE_SUFFIXES_REGEX = /\.(js|jsx|ts|tsx)$/
// Vite plugin for making React component names public on minified bundles.
// This plugin hooks into Vite's transform pipeline, parses the AST looking for
// React component definitions, and updates the source code to populate the
// displayName property. This property is used by the React Dev Tools extension
// to determine the name of a component.
function reactDisplayNamePlugin(options) {
const parsedOptions = new OptionsParser().parse(options)
return {
name: 'react-display-name-plugin',
// Run after other transforms (including JSX/TSX compilation)
enforce: 'post',
transform(code, id) {
// Ignore non-JS files
if (!VALID_FILE_SUFFIXES_REGEX.test(id.toLowerCase())) {
return null
}
// Apply include/exclude filters
if (parsedOptions.include.length &&
parsedOptions.include.every(match => !match(id))) {
return null
}
if (parsedOptions.exclude.length &&
parsedOptions.exclude.some(match => match(id))) {
return null
}
try {
// Parse the code into an AST
const ast = parse(code, {
ecmaVersion: 'latest',
sourceType: 'module',
locations: true,
ranges: true
})
// Collect all the display name injections we need to make
const injections = []
// Use shared component detection logic
detectReactComponents(ast, (node) => {
const componentName = node.id.name
const code = generateDisplayNameCode(componentName)
injections.push({
position: node.range[1],
code
})
})
// If no injections needed, return null (no transformation)
if (injections.length === 0) {
return null
}
// Sort injections by position (descending) so we insert from end to beginning
// This ensures positions remain valid as we modify the string
injections.sort((a, b) => b.position - a.position)
// Apply all injections
let modifiedCode = code
for (const injection of injections) {
modifiedCode =
modifiedCode.slice(0, injection.position) +
injection.code +
modifiedCode.slice(injection.position)
}
return {
code: modifiedCode,
map: null // Could generate source maps if needed
}
} catch (e) {
// If parsing fails, just return the original code
// This can happen with TypeScript or experimental syntax
console.warn(`[react-display-name-plugin] Failed to parse ${id}: ${e.message}`)
return null
}
}
}
}
module.exports = reactDisplayNamePlugin