-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathindex.ts
419 lines (370 loc) · 11 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import path from 'path'
import fs from 'fs'
import merge from 'lodash/merge'
import replaceExt from 'replace-ext'
import resolve from 'resolve'
import ensurePosix from 'ensure-posix-path'
import { urlToRequest } from 'loader-utils'
import webpack from 'webpack'
// @ts-ignore
import SingleEntryPlugin from 'webpack/lib/SingleEntryPlugin'
// @ts-ignore
import MultiEntryPlugin from 'webpack/lib/MultiEntryPlugin'
// @ts-ignore
import WebpackError from 'webpack/lib/WebpackError'
import compose from 'compose-function'
import { Minimatch } from 'minimatch'
import ConfigReader from './interfaces/config-reader'
import MinaConfigReader from './config-readers/mina'
import ClassicalConfigReader from './config-readers/classical'
import {
values,
uniq,
toSafeOutputPath,
getResourceUrlFromRequest,
removeSingleDot,
} from './helpers'
import { Entry, moveIntoSubpackage } from './helpers/entry'
const minaLoader = require.resolve('@tinajs/mina-loader')
const virtualMinaLoader = require.resolve('./loaders/virtual-mina-loader.js')
interface Extensions {
template: Array<string>
style: Array<string>
script: Array<string>
config: Array<string>
resolve: Array<string>
}
const DEFAULT_EXTENSIONS: Extensions = {
template: ['wxml'],
style: ['wxss'],
script: ['js'],
config: ['json'],
resolve: ['.js', '.wxml', '.json', '.wxss'],
}
const pluginPrefixReg = /(^(plugin|dynamicLib):\/\/)|(^weui-miniprogram\/)/;
function isAbsoluteUrl(url: string) {
return !!url.startsWith('/')
}
function addEntry(context: string, item: string | Array<string>, name: string) {
if (Array.isArray(item)) {
return new MultiEntryPlugin(context, item, name)
}
return new SingleEntryPlugin(context, item, name)
}
function getRequestsFromConfig(config: any) {
let requests: Array<string> = []
if (!config) {
return requests
}
;['pages', 'usingComponents', 'publicComponents'].forEach(key => {
if (typeof config[key] !== 'object') {
return
}
requests = [...requests, ...values(config[key])]
})
if (Array.isArray(config.subPackages)) {
config.subPackages.forEach((subPackage: any) => {
const { root, pages } = subPackage
if (Array.isArray(pages)) {
requests = [
...requests,
...pages.map(page => path.join(root || '', page)),
]
}
})
}
return uniq(requests)
}
const isMinaRequest = (request: string) => {
return path.extname(request) === '.mina'
}
// rootContext: /path/to/src
// currentContext: /path/to/src/pages
// `/components/demo` => `/path/to/src/components/demo` => `../components/demo`
// keeps `~@scope/package` or `./path/to/comp`
const resolveAbsoluteUrl = (
rootContext: string,
currentContext: string,
originalResourceUrl: string
) => {
if (isAbsoluteUrl(originalResourceUrl)) {
return path.relative(
currentContext,
path.resolve(rootContext, originalResourceUrl.slice(1))
)
}
return originalResourceUrl
}
const resolveRealPath = (
extensions: Extensions,
context: string,
originalUrl: string
) => {
const originalRequest = urlToRequest(originalUrl)
try {
let resourcePath: string
let isClassical: boolean
// mina component
try {
resourcePath = resolve.sync(originalRequest, {
basedir: context,
extensions: [],
})
isClassical = false
} catch (error) {
// classic component
resourcePath = resolve.sync(originalRequest, {
basedir: context,
extensions: extensions.resolve,
})
isClassical = true
}
return {
realPath: fs.realpathSync(resourcePath),
isClassical,
}
} catch (error) {
throw new MinaEntryPluginError(error)
}
}
const readConfig = (
rules: Array<{ pattern: string; reader: typeof ConfigReader }>,
rootContext: string,
resourcePath: string,
isClassical: boolean
) => {
let matchedRule = rules.find(({ pattern }) =>
pattern.match(path.relative(rootContext, resourcePath))
)
let config = matchedRule
? matchedRule.reader.getConfig(resourcePath)
: isClassical
? ClassicalConfigReader.getConfig(resourcePath)
: MinaConfigReader.getConfig(resourcePath)
return config
}
const getSubpackageRootsFromConfig = (config: any): Array<string> => {
if (!config) {
return []
}
const subpackages = config.subpackages || config.subPackages || []
return subpackages.map((item: { root?: string }) => item.root).filter(Boolean)
}
function getEntries(
rootContext: string,
entry: string,
rules: Array<{ pattern: string; reader: typeof ConfigReader }>,
extensions: Extensions,
minaLoaderOptions: Record<string, any>
) {
const entries: Array<Entry> = []
const errors: Array<MinaEntryPluginError> = []
let subpackageRoots: Array<string> = []
function search(
currentContext: string,
originalRequest: string,
parentEntry?: Entry
) {
// `any-loader!./index.mina` => `./index.mina`
const originalResourceUrl = getResourceUrlFromRequest(originalRequest)
// `/components/demo` => `/path/to/src/components/demo` => `../components/demo`
const resourceUrl = resolveAbsoluteUrl(
rootContext,
currentContext,
originalResourceUrl
)
// resolve symlink
let realPath: string
// mina or classic
let isClassical: boolean
try {
;({ realPath, isClassical } = resolveRealPath(
extensions,
currentContext,
resourceUrl
))
} catch (error) {
// Do not throw an exception when the module does not exist.
// Just mark it up and move on to the next module.
errors.push(error)
return
}
// relative path from rootContext, used to generate entry request or name
const relativeRealPath = path.relative(rootContext, realPath)
const relativeRealRequest = urlToRequest(relativeRealPath)
// generte request
let request: string
if (isClassical) {
request = `!${minaLoader}?${JSON.stringify(
minaLoaderOptions
)}!${virtualMinaLoader}?${JSON.stringify({
extensions,
})}!${relativeRealRequest}`
} else {
request = relativeRealRequest
}
// entry name for SingleEntryPlugin
// `../../path/to/comp` => `_/_/path/to/comp`
const name = compose(
ensurePosix,
(path: string) => replaceExt(path, '.js'),
removeSingleDot,
urlToRequest,
toSafeOutputPath
)(relativeRealPath)
// skip existing entries
const existingEntry = entries.find(item => item.request === request)
if (existingEntry) {
if (parentEntry) {
existingEntry.parents.push(parentEntry)
}
return
}
const entry: Entry = {
name,
realPath,
request,
parents: parentEntry ? [parentEntry] : [],
}
entries.push(entry)
const config = readConfig(rules, rootContext, realPath, isClassical)
let requests = getRequestsFromConfig(config)
// extra subpackage roots from app.json
if (!parentEntry) {
subpackageRoots = getSubpackageRootsFromConfig(config)
}
if (requests.length > 0) {
requests.forEach(req => {
if (pluginPrefixReg.test(req)) {
return
}
return search(path.dirname(realPath), req, entry)
})
}
}
search(rootContext, entry)
const { subpackageMapping } = moveIntoSubpackage(
rootContext,
subpackageRoots,
entries[0],
entries
)
return { entries, errors, subpackageMapping }
}
class MinaEntryPluginError extends WebpackError {
name: string
message: string
error: Error
constructor(error: Error) {
super()
this.name = 'MinaEntryPluginError'
this.message = `MinaEntryPlugin: ${error.message}`
this.error = error
Error.captureStackTrace(this, this.constructor)
}
}
interface MinaEntryWebpackPluginOptions {
map: (entry: string) => string | Array<string>
rules: Array<{ pattern: string; reader: typeof ConfigReader }>
extensions: Extensions
minaLoaderOptions: Record<string, any>
}
module.exports = class MinaEntryWebpackPlugin implements webpack.Plugin {
private _errors: Array<any>
private _items: Array<any>
private map: MinaEntryWebpackPluginOptions['map']
private rules: MinaEntryWebpackPluginOptions['rules']
private extensions: MinaEntryWebpackPluginOptions['extensions']
private minaLoaderOptions: MinaEntryWebpackPluginOptions['minaLoaderOptions']
constructor(options: Partial<MinaEntryWebpackPluginOptions> = {}) {
this.map =
options.map ||
function(entry: string) {
return entry
}
this.rules = (options.rules || []).map(rule => {
return Object.assign({}, rule, {
pattern: new Minimatch(rule.pattern, { matchBase: true }),
})
})
this.extensions = merge({}, DEFAULT_EXTENSIONS, options.extensions)
// TODO: redefine a better struct for this option
this.minaLoaderOptions = options.minaLoaderOptions || {}
this._errors = []
/**
* cache items to prevent duplicate `addEntry` operations
*/
this._items = []
}
rewrite(compiler: webpack.Compiler, done?: Function) {
try {
let { context, entry } = compiler.options
this._errors = []
// assume the latest file in array is the app.mina
if (Array.isArray(entry)) {
entry = entry[entry.length - 1]
}
const { entries, errors, subpackageMapping } = getEntries(
context!,
entry! as string,
this.rules,
this.extensions,
this.minaLoaderOptions
)
errors.forEach(item => {
this._errors.push(item.error)
})
entries.forEach(item => {
if (this._items.some(({ request }) => request === item.request)) {
return
}
this._items.push(item)
addEntry(
context!,
this.map(ensurePosix(item.request)),
item.name
).apply(compiler)
})
// inject subpackageMapping into loader context
if (compiler.hooks) {
compiler.hooks.compilation.tap('MinaEntryPlugin', compilation => {
let normalModuleLoader
if (Object.isFrozen(compilation.hooks)) {
// webpack 5
normalModuleLoader = require('webpack/lib/NormalModule').getCompilationHooks(
compilation
).loader
} else {
// webpack 4
normalModuleLoader = compilation.hooks.normalModuleLoader
}
normalModuleLoader.tap('MinaEntryPlugin', (loaderContext: any) => {
loaderContext.subpackageMapping = subpackageMapping
})
})
}
} catch (error) {
if (typeof done === 'function') {
console.error(error)
return done()
}
throw error
}
if (typeof done === 'function') {
done()
}
return true
}
apply(compiler: webpack.Compiler) {
compiler.hooks.entryOption.tap('MinaEntryPlugin', () =>
this.rewrite(compiler)
)
compiler.hooks.watchRun.tap('MinaEntryPlugin', (compiler, done) =>
this.rewrite(compiler, done)
)
compiler.hooks.compilation.tap('MinaEntryPlugin', compilation => {
this._errors.forEach(error => compilation.errors.push(error))
})
}
}
module.exports.ConfigReader = ConfigReader