-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathplugin.ts
205 lines (181 loc) · 5.78 KB
/
plugin.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
import type { Plugin, UserConfig } from 'vite'
import type { ViteSsrPluginOptions } from './config'
import type { SsrOptions } from './dev/server'
import { createSSRDevHandler } from './dev/server'
import { normalizePath } from 'vite'
const pluginName = 'vite-ssr'
const entryServer = '/entry-server'
const entryClient = '/entry-client'
export = function ViteSsrPlugin(
options: ViteSsrPluginOptions & SsrOptions = {}
) {
let detectedLib: 'core' | 'vue' | 'react'
const nameToMatch = options.plugin || pluginName
const autoEntryRE = new RegExp(`${nameToMatch}(\/core|\/vue|\/react)?$`)
const plugins = [
{
name: pluginName,
enforce: 'pre',
viteSsrOptions: options,
config(config, env) {
const plugins = config.plugins as Plugin[]
const isVue = hasPlugin(plugins, 'vite:vue')
const isReact =
hasPlugin(plugins, 'vite:react') ||
hasPlugin(plugins, 'react-refresh')
detectedLib = isVue ? 'vue' : isReact ? 'react' : 'core'
const detectedFeats = {
...(isReact && detectReactConfigFeatures(options.features)),
}
return {
...detectedFeats,
define: {
...detectedFeats.define,
__CONTAINER_ID__: JSON.stringify(options.containerId || 'app'),
// Vite 2.6.0 bug: use this
// instead of import.meta.env.DEV
__VITE_SSR_DEV__: env.mode !== 'production',
},
ssr: {
...detectedFeats.ssr,
noExternal: [pluginName],
},
server:
// Avoid displaying 'localhost' in terminal in MacOS:
// https://github.com/vitejs/vite/issues/5605
process.platform === 'darwin'
? {
host: config.server?.host || '127.0.0.1',
}
: undefined,
}
},
configResolved: (config) => {
const libPath = `/${detectedLib}`
// @ts-ignore
config.optimizeDeps = config.optimizeDeps || {}
config.optimizeDeps.include = config.optimizeDeps.include || []
config.optimizeDeps.include.push(
nameToMatch + libPath + entryClient,
nameToMatch + libPath + entryServer
)
if (detectedLib === 'react') {
fixReactDeps(config, libPath)
}
},
async configureServer(server) {
if (process.env.__DEV_MODE_SSR) {
const handler = createSSRDevHandler(server, options)
return () => server.middlewares.use(handler)
}
},
// Implement auto-entry using virtual modules:
resolveId(source, importer, options) {
if (source.includes(nameToMatch)) {
source = normalizePath(source)
if (autoEntryRE.test(source)) {
return `virtual:${source}/index.js`
}
}
},
load(id, options) {
if (id.startsWith(`virtual:${nameToMatch}`)) {
id = normalizePath(id)
let [, lib = ''] = id.split('/')
if (lib === 'index.js') {
lib = detectedLib
}
const libPath = `'${nameToMatch}/${lib}/entry-${
options?.ssr ? 'server' : 'client'
}'`
return `export * from ${libPath}; export { default } from ${libPath}`
}
},
},
] as Array<Plugin & Record<string, any>>
if ((options.excludeSsrComponents || []).length > 0) {
plugins.push({
name: pluginName + '-exclude-components',
enforce: 'pre',
resolveId(source, importer, ...rest) {
// @ts-ignore
const ssr = rest[1] || rest[0]?.ssr // API changed in Vite 2.7 https://github.com/vitejs/vite/pull/5294
if (
ssr &&
options.excludeSsrComponents!.some((re) => re.test(source))
) {
return this.resolve(
`${pluginName}/${detectedLib}/ssr-component-mock`,
importer,
{ skipSelf: true }
)
}
},
})
}
return plugins
}
function hasPlugin(plugins: Plugin[] | Plugin[][] = [], name: string): boolean {
return !!plugins.flat().find((plugin) => (plugin.name || '').startsWith(name))
}
function hasDependency(dependency: string) {
try {
require.resolve(dependency)
return true
} catch (error) {
return false
}
}
function detectReactConfigFeatures(
features: ViteSsrPluginOptions['features'] = {}
) {
const external = []
let useApolloRenderer
// TODO use virtual modules for feature-detection
if (hasDependency('@apollo/client/react/ssr')) {
useApolloRenderer = features.reactApolloRenderer !== false
} else {
external.push('@apollo/client')
}
return {
ssr: { external },
define: {
__USE_APOLLO_RENDERER__: !!useApolloRenderer,
},
}
}
// FIXME
// Vite 2.6.0 introduced a bug where `import.meta` is not populated
// correctly in optimized dependencies. At the same time, all the
// subdependencies in Style Collectors must be optimized.
function fixReactDeps(
config: Pick<UserConfig, 'optimizeDeps' | 'root'>,
libPath: string
) {
const styleCollectorDeps = {
'styled-components': ['styled-components'],
'material-ui-core-v4': ['@material-ui/core/styles'],
emotion: ['@emotion/cache', '@emotion/react'],
} as const
const styleCollectors = Object.keys(styleCollectorDeps).filter((sc) => {
try {
require.resolve(sc)
return true
} catch (error) {
return false
}
})
if (config.optimizeDeps) {
config.optimizeDeps.include?.push(
...styleCollectors.flatMap(
(sc) => styleCollectorDeps[sc as keyof typeof styleCollectorDeps]
)
)
config.optimizeDeps.exclude = config.optimizeDeps.exclude || []
config.optimizeDeps.exclude.push(
...styleCollectors.map(
(sc) => pluginName + libPath + '/style-collectors/' + sc
)
)
}
}