-
-
Notifications
You must be signed in to change notification settings - Fork 899
/
Copy pathcode-splitter.ts
230 lines (190 loc) · 6.12 KB
/
code-splitter.ts
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import { isAbsolute, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import {
compileCodeSplitReferenceRoute,
compileCodeSplitVirtualRoute,
} from './compilers'
import { getConfig } from './config'
import { splitPrefix } from './constants'
import type { Config } from './config'
import type { UnpluginContextMeta, UnpluginFactory } from 'unplugin'
function capitalizeFirst(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1)
}
function fileIsInRoutesDirectory(filePath: string, routesDirectory: string) {
const routesDirectoryPath = isAbsolute(routesDirectory)
? routesDirectory
: join(process.cwd(), routesDirectory)
return filePath.startsWith(routesDirectoryPath)
}
type BannedBeforeExternalPlugin = {
identifier: string
pkg: string
usage: string
frameworks: Array<UnpluginContextMeta['framework']>
}
const bannedBeforeExternalPlugins: Array<BannedBeforeExternalPlugin> = [
{
identifier: '@react-refresh',
pkg: '@vitejs/plugin-react',
usage: 'viteReact()',
frameworks: ['vite'],
},
]
class FoundPluginInBeforeCode extends Error {
constructor(externalPlugin: BannedBeforeExternalPlugin, framework: string) {
super(`We detected that the '${externalPlugin.pkg}' was passed before '@tanstack/router-plugin'. Please make sure that '@tanstack/router-plugin' is passed before '${externalPlugin.pkg}' and try again:
e.g.
plugins: [
TanStackRouter${capitalizeFirst(framework)}(), // Place this before ${externalPlugin.usage}
${externalPlugin.usage},
]
`)
}
}
const PLUGIN_NAME = 'unplugin:router-code-splitter'
const JoinedSplitPrefix = splitPrefix + ':'
export const unpluginRouterCodeSplitterFactory: UnpluginFactory<
Partial<Config> | undefined
> = (options = {}, { framework }) => {
const debug = Boolean(process.env.TSR_VITE_DEBUG)
let ROOT: string = process.cwd()
let userConfig = options as Config
const handleSplittingFile = async (code: string, id: string) => {
if (debug) console.info('Splitting route: ', id)
const compiledVirtualRoute = compileCodeSplitVirtualRoute({
code,
root: ROOT,
filename: id,
})
if (debug) console.info('')
if (debug) console.info('Split Output')
if (debug) console.info('')
if (debug) console.info(compiledVirtualRoute.code)
if (debug) console.info('')
if (debug) console.info('')
if (debug) console.info('')
return compiledVirtualRoute
}
const handleCompilingFile = async (code: string, id: string) => {
if (debug) console.info('Handling createRoute: ', id)
const compiledReferenceRoute = compileCodeSplitReferenceRoute({
code,
root: ROOT,
filename: id,
})
if (debug) console.info('')
if (debug) console.info('Compiled Output')
if (debug) console.info('')
if (debug) console.info(compiledReferenceRoute.code)
if (debug) console.info('')
if (debug) console.info('')
if (debug) console.info('')
return compiledReferenceRoute
}
return {
name: 'router-code-splitter-plugin',
enforce: 'pre',
resolveId(source) {
if (!userConfig.experimental?.enableCodeSplitting) {
return null
}
if (source.startsWith(splitPrefix + ':')) {
return source.replace(splitPrefix + ':', '')
}
return null
},
async transform(code, id) {
if (!userConfig.experimental?.enableCodeSplitting) {
return null
}
const url = pathToFileURL(id)
url.searchParams.delete('v')
id = fileURLToPath(url).replace(/\\/g, '/')
if (id.includes(splitPrefix)) {
return await handleSplittingFile(code, id)
} else if (
fileIsInRoutesDirectory(id, userConfig.routesDirectory) &&
(code.includes('createRoute(') || code.includes('createFileRoute('))
) {
for (const externalPlugin of bannedBeforeExternalPlugins) {
if (!externalPlugin.frameworks.includes(framework)) {
continue
}
if (code.includes(externalPlugin.identifier)) {
throw new FoundPluginInBeforeCode(externalPlugin, framework)
}
}
return await handleCompilingFile(code, id)
}
return null
},
transformInclude(transformId) {
if (!userConfig.experimental?.enableCodeSplitting) {
return undefined
}
let id = transformId
if (id.startsWith(JoinedSplitPrefix)) {
id = id.replace(JoinedSplitPrefix, '')
}
if (
fileIsInRoutesDirectory(id, userConfig.routesDirectory) ||
id.includes(splitPrefix)
) {
return true
}
return false
},
vite: {
async configResolved(config) {
ROOT = config.root
userConfig = await getConfig(options, ROOT)
},
},
async rspack(compiler) {
ROOT = process.cwd()
compiler.hooks.beforeCompile.tap(PLUGIN_NAME, (self) => {
self.normalModuleFactory.hooks.beforeResolve.tap(
PLUGIN_NAME,
(resolveData) => {
if (resolveData.request.includes(JoinedSplitPrefix)) {
resolveData.request = resolveData.request.replace(
JoinedSplitPrefix,
'',
)
}
},
)
})
userConfig = await getConfig(options, ROOT)
},
async webpack(compiler) {
ROOT = process.cwd()
compiler.hooks.beforeCompile.tap(PLUGIN_NAME, (self) => {
self.normalModuleFactory.hooks.beforeResolve.tap(
PLUGIN_NAME,
(resolveData) => {
if (resolveData.request.includes(JoinedSplitPrefix)) {
resolveData.request = resolveData.request.replace(
JoinedSplitPrefix,
'',
)
}
},
)
})
userConfig = await getConfig(options, ROOT)
if (
userConfig.experimental?.enableCodeSplitting &&
compiler.options.mode === 'production'
) {
compiler.hooks.done.tap(PLUGIN_NAME, (stats) => {
console.log('✅ ' + PLUGIN_NAME + ': code-splitting done!')
setTimeout(() => {
process.exit(0)
})
})
}
},
}
}