-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathlazy-load.ts
More file actions
207 lines (186 loc) · 7.76 KB
/
lazy-load.ts
File metadata and controls
207 lines (186 loc) · 7.76 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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import { genImport } from 'knitwork'
import MagicString from 'magic-string'
import { parse, resolve } from 'node:path'
import { parseSync, type CallExpression, type ImportDeclaration, type ImportDefaultSpecifier, type ImportSpecifier } from 'oxc-parser'
import { createUnplugin } from 'unplugin'
import { distDir } from '../dirs'
import { findDefineComponentCalls } from './utils'
import { useNuxt } from '@nuxt/kit'
import type { Component } from '@nuxt/schema'
const INCLUDE_FILES = /\.(vue|tsx?|jsx?)$/
// Exclude node_moduels as users can have control over it
const EXCLUDE_NODE_MODULES = /node_modules/
const skipPath = normalizePath(resolve(distDir, 'runtime/lazy-load'))
export const LazyLoadHintPlugin = createUnplugin(() => {
const nuxt = useNuxt()
let nuxtComponents: Component[] = nuxt.apps.default!.components
nuxt.hook('components:extend', (extendedComponents) => {
nuxtComponents = extendedComponents
})
return {
name: '@nuxt/hints:lazy-load-plugin',
enforce: 'post',
transform: {
filter: {
id: {
include: INCLUDE_FILES,
exclude: [skipPath, EXCLUDE_NODE_MODULES],
},
},
handler(code, id) {
const m = new MagicString(code)
const { program } = parseSync(id, code)
const imports = program.body.filter(
(node): node is ImportDeclaration => node.type === 'ImportDeclaration',
)
const directComponentImports: {
name: string
source: string
start: number
end: number
specifier: ImportDefaultSpecifier | ImportSpecifier
}[] = []
for (const importDecl of imports) {
const source = importDecl.source.value
// Skip if not a .vue file import
if (!source.endsWith('.vue')) continue
if (importDecl.importKind === 'type') continue
for (const specifier of importDecl.specifiers ?? []) {
if (specifier.type === 'ImportDefaultSpecifier' || specifier.type === 'ImportSpecifier') {
const localName = specifier.local.name
directComponentImports.push({
name: localName,
source,
start: importDecl.start,
end: importDecl.end,
specifier,
})
}
}
}
if (directComponentImports.length === 0) {
return
}
// Inject the tracking wrapper import
m.prepend(genImport(
'@nuxt/hints/runtime/lazy-load/composables',
['__wrapImportedComponent', '__wrapMainComponent'],
) + '\n' + genImport(
'@nuxt/hints/runtime/lazy-load/composables',
['useLazyComponentTracking'],
) + '\n')
// For each direct import, wrap the component to track its usage
// We do this after the imports by adding wrapper statements
const wrapperStatements = directComponentImports
.map((imp) => {
const originalName = `__original_${imp.name}`
const resolvedName = resolveComponentName(imp, nuxtComponents)
// Rename the import to __original_X and create a wrapped version as X
return `const ${imp.name} = __wrapImportedComponent(${originalName}, '${resolvedName}', '${imp.source}', '${normalizePath(id)}')`
})
.join('\n')
// Rename original imports by modifying the import specifiers
for (const imp of directComponentImports) {
const specifier = imp.specifier
const localName = specifier.local.name
const newName = `__original_${localName}`
if (specifier.type === 'ImportDefaultSpecifier') {
// For default imports: `import X from` → `import __original_X from`
m.overwrite(
specifier.local.start,
specifier.local.end,
newName,
)
}
else if (specifier.type === 'ImportSpecifier' && specifier.imported.type === 'Identifier' && specifier.imported.name !== specifier.local.name) {
// For aliased imports: `import { X as Y }` or `import { default as X }` → `import { X as __original_Y }` or `import { default as __original_X }`
m.overwrite(
specifier.local.start,
specifier.local.end,
newName,
)
}
else {
// For named imports: `import { X }` → `import { X as __original_X }`
m.overwrite(
specifier.local.start,
specifier.local.end,
`${localName} as ${newName}`,
)
}
}
// Inject useLazyComponentTracking in main component setup if applicable
if (code.includes('_sfc_main')) {
const wrappedComponents = directComponentImports.map((imp) => {
const componentName = resolveComponentName(imp, nuxtComponents)
return `{ componentName: '${componentName}', importSource: '${imp.source}', importedBy: '${normalizePath(id)}', rendered: false }`
}).join(', ')
m.replace('export default _sfc_main', `const _sfc_main_wrapped = __wrapMainComponent(_sfc_main, [${wrappedComponents}]);\nexport default _sfc_main_wrapped`)
}
const components = findDefineComponentCalls(program)
if (components && components.length > 0) {
for (const comp of components) {
injectUseLazyComponentTrackingInComponentSetup(comp, m, directComponentImports, id, nuxtComponents)
}
}
const lastImport = imports[imports.length - 1]
// See https://github.com/nuxt/hints/issues/241
if (lastImport) {
m.appendRight(lastImport.end, '\n' + wrapperStatements)
}
else {
m.prepend(wrapperStatements + '\n')
}
if (m.hasChanged()) {
return {
code: m.toString(),
map: m.generateMap({ hires: true }),
}
}
},
},
}
})
function normalizePath(path: string): string {
return path.replace(/\\/g, '/')
}
function resolveComponentName(
imp: { name: string, source: string },
nuxtComponents: Component[],
): string {
const component = nuxtComponents.find(c => c.filePath === imp.source)
if (component) return component.pascalName
return imp.name.startsWith('__nuxt') ? parse(imp.source).name : imp.name
}
function injectUseLazyComponentTrackingInComponentSetup(node: CallExpression, magicString: MagicString, directComponentImports: {
name: string
source: string
start: number
end: number
specifier: ImportDefaultSpecifier | ImportSpecifier
}[], id: string, nuxtComponents: Component[]) {
if (node.arguments.length === 1) {
const arg = node.arguments[0]
if (arg?.type === 'ObjectExpression') {
const properties = arg.properties
const setupProp = properties.find(prop =>
prop.type === 'Property'
&& prop.key.type === 'Identifier'
&& prop.key.name === 'setup',
)
if (setupProp && setupProp.type === 'Property') {
const setupFunc = setupProp.value
if (setupFunc.type === 'FunctionExpression' || setupFunc.type === 'ArrowFunctionExpression') {
// Inject useLazyComponentTracking call at the start of the setup function body
const insertPos = (setupFunc.body?.start ?? 0) + 1 // after {
const componentsArray = directComponentImports.map((imp) => {
const componentName = resolveComponentName(imp, nuxtComponents)
return `{ componentName: '${componentName}', importSource: '${imp.source}', importedBy: '${normalizePath(id)}', rendered: false }`
}).join(', ')
const injectionCode = `\nconst lazyHydrationState = useLazyComponentTracking([${componentsArray}]);\n`
magicString.appendLeft(insertPos, injectionCode)
}
}
}
}
}