-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathindex.ts
232 lines (201 loc) · 9.3 KB
/
index.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
231
232
import type { ResolvePluginInstance, Resolver } from 'webpack'
import type { ResolvedUnpluginOptions, UnpluginContext, UnpluginContextMeta, UnpluginFactory, UnpluginInstance, WebpackCompiler } from '../types'
import fs from 'node:fs'
import { resolve } from 'node:path'
import process from 'node:process'
import VirtualModulesPlugin from 'webpack-virtual-modules'
import { toArray } from '../utils/general'
import { normalizeAbsolutePath, transformUse } from '../utils/webpack-like'
import { contextOptionsFromCompilation, createBuildContext, normalizeMessage } from './context'
const TRANSFORM_LOADER = resolve(
__dirname,
__DEV__ ? '../../dist/webpack/loaders/transform' : 'webpack/loaders/transform',
)
const LOAD_LOADER = resolve(
__dirname,
__DEV__ ? '../../dist/webpack/loaders/load' : 'webpack/loaders/load',
)
export function getWebpackPlugin<UserOptions = Record<string, never>>(
factory: UnpluginFactory<UserOptions>,
): UnpluginInstance<UserOptions>['webpack'] {
return (userOptions?: UserOptions) => {
return {
apply(compiler: WebpackCompiler) {
// We need the prefix of virtual modules to be an absolute path so webpack let's us load them (even if it's made up)
// In the loader we strip the made up prefix path again
const VIRTUAL_MODULE_PREFIX = resolve(compiler.options.context ?? process.cwd(), '_virtual_')
const meta: UnpluginContextMeta = {
framework: 'webpack',
webpack: {
compiler,
},
}
const rawPlugins = toArray(factory(userOptions!, meta))
for (const rawPlugin of rawPlugins) {
const plugin = Object.assign(
rawPlugin,
{
__unpluginMeta: meta,
__virtualModulePrefix: VIRTUAL_MODULE_PREFIX,
},
) as ResolvedUnpluginOptions
const externalModules = new Set<string>()
// resolveId hook
if (plugin.resolveId) {
let vfs = compiler.options.plugins.find(i => i instanceof VirtualModulesPlugin) as VirtualModulesPlugin
if (!vfs) {
vfs = new VirtualModulesPlugin()
compiler.options.plugins.push(vfs)
}
plugin.__vfsModules = new Set()
plugin.__vfs = vfs
const resolverPlugin: ResolvePluginInstance = {
apply(resolver: Resolver) {
const target = resolver.ensureHook('resolve')
resolver
.getHook('resolve')
.tapAsync(plugin.name, async (request, resolveContext, callback) => {
if (!request.request)
return callback()
// filter out invalid requests
if (normalizeAbsolutePath(request.request).startsWith(plugin.__virtualModulePrefix))
return callback()
const id = normalizeAbsolutePath(request.request)
const requestContext = (request as unknown as { context: { issuer: string } }).context
let importer = requestContext.issuer !== '' ? requestContext.issuer : undefined
const isEntry = requestContext.issuer === ''
if (importer?.startsWith(plugin.__virtualModulePrefix))
importer = decodeURIComponent(importer.slice(plugin.__virtualModulePrefix.length))
// call hook
// resolveContext.fileDependencies is typed as a WriteOnlySet, so make our own copy here
// so we can return it from getWatchFiles.
const fileDependencies = new Set<string>()
const context = createBuildContext({
addWatchFile(file) {
fileDependencies.add(file)
resolveContext.fileDependencies?.add(file)
},
getWatchFiles() {
return Array.from(fileDependencies)
},
}, compiler)
let error: Error | undefined
const pluginContext: UnpluginContext = {
error(msg) {
if (error == null)
error = normalizeMessage(msg)
else
console.error(`unplugin/webpack: multiple errors returned from resolveId hook: ${msg}`)
},
warn(msg) {
console.warn(`unplugin/webpack: warning from resolveId hook: ${msg}`)
},
}
const resolveIdResult = await plugin.resolveId!.call!({ ...context, ...pluginContext }, id, importer, { isEntry })
if (error != null)
return callback(error)
if (resolveIdResult == null)
return callback()
let resolved = typeof resolveIdResult === 'string' ? resolveIdResult : resolveIdResult.id
const isExternal = typeof resolveIdResult === 'string' ? false : resolveIdResult.external === true
if (isExternal)
externalModules.add(resolved)
// If the resolved module does not exist,
// we treat it as a virtual module
if (!fs.existsSync(resolved)) {
resolved = normalizeAbsolutePath(
plugin.__virtualModulePrefix
+ encodeURIComponent(resolved), // URI encode id so webpack doesn't think it's part of the path
)
// webpack virtual module should pass in the correct path
// https://github.com/unjs/unplugin/pull/155
if (!plugin.__vfsModules!.has(resolved)) {
plugin.__vfs!.writeModule(resolved, '')
plugin.__vfsModules!.add(resolved)
}
}
// construct the new request
const newRequest = {
...request,
request: resolved,
}
// redirect the resolver
resolver.doResolve(target, newRequest, null, resolveContext, callback)
})
},
}
compiler.options.resolve.plugins = compiler.options.resolve.plugins || []
compiler.options.resolve.plugins.push(resolverPlugin)
}
// load hook
if (plugin.load) {
compiler.options.module.rules.unshift({
include(id) {
return shouldLoad(id, plugin, externalModules)
},
enforce: plugin.enforce,
use: [{
loader: LOAD_LOADER,
options: {
plugin,
},
}],
type: 'javascript/auto',
})
}
// transform hook
if (plugin.transform) {
compiler.options.module.rules.unshift({
enforce: plugin.enforce,
use(data: { resource?: string, resourceQuery?: string }) {
return transformUse(data, plugin, TRANSFORM_LOADER)
},
})
}
if (plugin.webpack)
plugin.webpack(compiler)
if (plugin.watchChange || plugin.buildStart) {
compiler.hooks.make.tapPromise(plugin.name, async (compilation) => {
const context = createBuildContext(contextOptionsFromCompilation(compilation), compiler, compilation)
if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) {
const promises: Promise<void>[] = []
if (compiler.modifiedFiles) {
compiler.modifiedFiles.forEach(file =>
promises.push(Promise.resolve(plugin.watchChange!.call(context, file, { event: 'update' }))),
)
}
if (compiler.removedFiles) {
compiler.removedFiles.forEach(file =>
promises.push(Promise.resolve(plugin.watchChange!.call(context, file, { event: 'delete' }))),
)
}
await Promise.all(promises)
}
if (plugin.buildStart)
return await plugin.buildStart.call(context)
})
}
if (plugin.buildEnd) {
compiler.hooks.emit.tapPromise(plugin.name, async (compilation) => {
await plugin.buildEnd!.call(createBuildContext(contextOptionsFromCompilation(compilation), compiler, compilation))
})
}
if (plugin.writeBundle) {
compiler.hooks.afterEmit.tapPromise(plugin.name, async () => {
await plugin.writeBundle!()
})
}
}
},
}
}
}
export function shouldLoad(id: string, plugin: ResolvedUnpluginOptions, externalModules: Set<string>): boolean {
if (id.startsWith(plugin.__virtualModulePrefix))
id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length))
// load include filter
if (plugin.loadInclude && !plugin.loadInclude(id))
return false
// Don't run load hook for external modules
return !externalModules.has(id)
}