-
Notifications
You must be signed in to change notification settings - Fork 389
Expand file tree
/
Copy pathindex.js
More file actions
724 lines (675 loc) · 23.8 KB
/
Copy pathindex.js
File metadata and controls
724 lines (675 loc) · 23.8 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
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
const async = require('async')
const JSON5 = require('json5')
const path = require('path')
const parseComponent = require('../parser')
const config = require('../config')
const parseRequest = require('../utils/parse-request')
const evalJSONJS = require('../utils/eval-json-js')
const getRulesRunner = require('../platform/index')
const addQuery = require('../utils/add-query')
const getJSONContent = require('../utils/get-json-content')
const createHelpers = require('../helpers')
const createJSONHelper = require('./helper')
const RecordIndependentDependency = require('../dependencies/RecordIndependentDependency')
const RecordRuntimeInfoDependency = require('../dependencies/RecordRuntimeInfoDependency')
const { MPX_DISABLE_EXTRACTOR_CACHE, RESOLVE_IGNORED_ERR, JSON_JS_EXT } = require('../utils/const')
const resolve = require('../utils/resolve')
const resolveTabBarPath = require('../utils/resolve-tab-bar-path')
const resolveMpxCustomElementPath = require('../utils/resolve-mpx-custom-element-path')
module.exports = function (content) {
const nativeCallback = this.async()
const mpx = this.getMpx()
if (!mpx) {
return nativeCallback(null, content)
}
// json模块必须每次都创建(但并不是每次都需要build),用于动态添加编译入口,传递信息以禁用父级extractor的缓存
this.emitFile(MPX_DISABLE_EXTRACTOR_CACHE, '', undefined, { skipEmit: true })
// 微信插件下要求组件使用相对路径
const useRelativePath = mpx.isPluginMode || mpx.useRelativePath
const { resourcePath, queryObj } = parseRequest(this.resource)
const useJSONJS = queryObj.useJSONJS || this.resourcePath.endsWith(JSON_JS_EXT)
const packageName = queryObj.packageRoot || mpx.currentPackageRoot || 'main'
const pagesMap = mpx.pagesMap
const componentsMap = mpx.componentsMap[packageName]
const appInfo = mpx.appInfo
const mode = mpx.mode
const env = mpx.env
const globalSrcMode = mpx.srcMode
const localSrcMode = queryObj.mode
const srcMode = localSrcMode || globalSrcMode
const isApp = !(pagesMap[resourcePath] || componentsMap[resourcePath])
const publicPath = this._compilation.outputOptions.publicPath || ''
const fs = this._compiler.inputFileSystem
const runtimeCompile = queryObj.isDynamic
const emitWarning = (msg, loc) => {
this.emitWarning(
new Error('[Mpx json error][' + (loc || this.resourcePath) + ']: ' + msg)
)
}
const emitError = (msg, loc) => {
this.emitError(
new Error('[Mpx json error][' + (loc || this.resourcePath) + ']: ' + msg)
)
}
const {
isUrlRequest,
urlToRequest,
processPage,
processDynamicEntry,
processComponent,
processJsExport,
processPlaceholder
} = createJSONHelper({
loaderContext: this,
emitWarning,
emitError
})
const { getRequestString } = createHelpers(this)
let currentName
if (isApp) {
currentName = appInfo.name
} else {
currentName = componentsMap[resourcePath] || pagesMap[resourcePath]
}
const relativePath = useRelativePath ? publicPath + path.dirname(currentName) : ''
const copydir = (dir, context, callback) => {
fs.readdir(dir, (err, files) => {
if (err) return callback(err)
async.each(files, (file, callback) => {
file = path.join(dir, file)
async.waterfall([
(callback) => {
fs.stat(file, callback)
},
(stats, callback) => {
if (stats.isDirectory()) {
copydir(file, context, callback)
} else {
fs.readFile(file, (err, content) => {
if (err) return callback(err)
if (!this._compilation) return callback()
const targetPath = path.relative(context, file)
this.emitFile(targetPath, content)
callback()
})
}
}
], callback)
}, callback)
})
}
const callback = (err, processOutput) => {
if (err) return nativeCallback(err)
let output = `var json = ${JSON.stringify(json, null, 2)};\n`
if (processOutput) output = processOutput(output)
const jsonSpace = this.minimize ? 0 : 2
output += `module.exports = JSON.stringify(json, null, ${jsonSpace});\n`
nativeCallback(null, output)
}
let json
try {
if (useJSONJS) {
json = evalJSONJS(content, this.resourcePath, this)
} else {
json = JSON5.parse(content || '{}')
}
} catch (err) {
return callback(err)
}
// json补全
if (pagesMap[resourcePath]) {
// page
if (!mpx.forceUsePageCtor) {
if (!json.usingComponents) {
json.usingComponents = {}
}
if (!json.component && mode === 'swan') {
json.component = true
}
}
} else if (componentsMap[resourcePath]) {
// component
if (json.component !== true) {
json.component = true
}
}
const dependencyComponentsMap = {}
if (queryObj.mpxCustomElement) {
this.cacheable(false)
mpx.collectDynamicSlotDependencies(packageName)
}
if (runtimeCompile) {
json.usingComponents = json.usingComponents || {}
}
// 快应用补全json配置,必填项
if (mode === 'qa' && isApp) {
const defaultConf = {
package: '',
name: '',
icon: 'assets/images/logo.png',
versionName: '',
versionCode: 1,
minPlatformVersion: 1080
}
json = Object.assign({}, defaultConf, json)
}
const rulesRunnerOptions = {
mode,
srcMode,
type: 'json',
waterfall: true,
warn: emitWarning,
error: emitError,
diagnostic: {
file: resourcePath
},
data: {
// polyfill global usingComponents
globalComponents: mpx.globalComponents
}
}
if (!isApp) {
rulesRunnerOptions.mainKey = pagesMap[resourcePath] ? 'page' : 'component'
}
const rulesRunner = getRulesRunner(rulesRunnerOptions)
if (rulesRunner) {
rulesRunner(json)
}
const processComponents = (components, context, callback) => {
if (components) {
// 存在所有命中asyncSubpackageRules的组件
const asyncComponents = []
const resolveResourcePathMap = new Map()
async.eachOf(components, (component, name, callback) => {
processComponent(component, context, { relativePath }, (err, entry, { tarRoot, placeholder, resourcePath, queryObj = {} } = {}) => {
if (err === RESOLVE_IGNORED_ERR) {
delete components[name]
return callback()
}
if (err) return callback(err)
components[name] = entry
if (runtimeCompile) {
// 替换组件的 hashName,并删除原有的组件配置
const hashName = 'm' + mpx.pathHash(resourcePath)
components[hashName] = entry
delete components[name]
dependencyComponentsMap[name] = {
hashName,
resourcePath,
isDynamic: queryObj.isDynamic
}
}
resolveResourcePathMap.set(name, resourcePath)
if (tarRoot) asyncComponents.push({ name, tarRoot, placeholder, relativePath })
callback()
})
}, (err) => {
if (err) return callback(err)
const mpxCustomElementPath = resolveMpxCustomElementPath(packageName)
if (runtimeCompile) {
components.element = mpxCustomElementPath
components.mpx_dynamic_slot = '' // 运行时组件打标记,在 processAssets 统一替换
this._module.addPresentationalDependency(new RecordRuntimeInfoDependency(packageName, resourcePath, { type: 'json', info: dependencyComponentsMap }))
}
if (queryObj.mpxCustomElement) {
components.element = mpxCustomElementPath
Object.assign(components, mpx.getPackageInjectedComponentsMap(packageName))
}
// 使用async处理所有asyncComponents完成后调用callback
async.each(asyncComponents, ({ name, tarRoot, placeholder, relativePath }, callback) => {
processPlaceholder({ jsonObj: json, context, name, tarRoot, placeholder, relativePath, resolveResourcePathMap }, callback)
}, callback)
})
} else {
callback()
}
}
if (isApp) {
// app.json
const localPages = []
const subPackagesCfg = {}
const pageKeySet = new Set()
const defaultPagePath = require.resolve('../runtime/components/wx/default-page.mpx')
const processPages = (pages, context, tarRoot = '', callback) => {
if (pages) {
const pagesCache = []
async.each(pages, (page, callback) => {
processPage(page, context, tarRoot, (err, entry, { isFirst, key, resource } = {}) => {
if (err) return callback(err === RESOLVE_IGNORED_ERR ? null : err)
if (pageKeySet.has(key)) return callback()
if (resource.startsWith(defaultPagePath)) {
pagesCache.push(entry)
return callback()
}
pageKeySet.add(key)
if (tarRoot && subPackagesCfg) {
subPackagesCfg[tarRoot].pages.push(entry)
} else {
// 确保首页
if (isFirst) {
localPages.unshift(entry)
} else {
localPages.push(entry)
}
}
callback()
})
}, (err) => {
if (err) return callback(err)
if (tarRoot && subPackagesCfg) {
if (!subPackagesCfg[tarRoot].pages.length && pagesCache[0]) {
subPackagesCfg[tarRoot].pages.push(pagesCache[0])
}
} else {
if (!localPages.length && pagesCache[0]) {
localPages.push(pagesCache[0])
}
}
callback()
})
} else {
callback()
}
}
const processPackages = (packages, context, callback) => {
if (packages) {
async.each(packages, (packagePath, callback) => {
const { queryObj } = parseRequest(packagePath)
async.waterfall([
(callback) => {
resolve(context, packagePath, this, (err, result) => {
if (err) return callback(err)
const { rawResourcePath } = parseRequest(result)
callback(err, rawResourcePath)
})
},
(result, callback) => {
fs.readFile(result, (err, content) => {
if (err) return callback(err)
callback(err, result, content.toString('utf-8'))
})
},
(result, content, callback) => {
const extName = path.extname(result)
if (extName === '.mpx') {
const parts = parseComponent(content, {
filePath: result,
needMap: this.sourceMap,
mode,
env
})
// 对于通过.mpx文件声明的独立分包,默认将其自身的script block视为init module
if (queryObj.independent === true) queryObj.independent = result
getJSONContent(parts.json || {}, result, this, (err, content) => {
callback(err, result, content)
})
} else {
callback(null, result, content)
}
},
(result, content, callback) => {
try {
content = JSON5.parse(content)
} catch (err) {
return callback(err)
}
const processSelfQueue = []
const context = path.dirname(result)
if (content.pages) {
const tarRoot = queryObj.root
if (tarRoot) {
delete queryObj.root
const subPackage = {
tarRoot,
pages: content.pages,
...queryObj
}
if (content.plugins) {
subPackage.plugins = content.plugins
}
processSelfQueue.push((callback) => {
processSubPackage(subPackage, context, callback)
})
} else {
processSelfQueue.push((callback) => {
processPages(content.pages, context, '', callback)
})
}
}
if (content.packages) {
processSelfQueue.push((callback) => {
processPackages(content.packages, context, callback)
})
}
if (processSelfQueue.length) {
async.parallel(processSelfQueue, callback)
} else {
callback()
}
}
], (err) => {
callback(err === RESOLVE_IGNORED_ERR ? null : err)
})
}, callback)
} else {
callback()
}
}
const getOtherConfig = (config) => {
const result = {}
const blackListMap = {
tarRoot: true,
srcRoot: true,
root: true,
pages: true
}
for (const key in config) {
if (!blackListMap[key]) {
result[key] = config[key]
}
}
return result
}
const recordIndependent = (root, request) => {
this._module && this._module.addPresentationalDependency(new RecordIndependentDependency(root, request))
}
const processIndependent = (otherConfig, context, tarRoot, callback) => {
// 支付宝不支持独立分包,无需处理
const independent = otherConfig.independent
if (!independent || mode === 'ali') {
delete otherConfig.independent
return callback()
}
// independent配置为字符串时视为init module
if (typeof independent === 'string') {
otherConfig.independent = true
resolve(context, independent, this, (err, result) => {
if (err) return callback(err)
recordIndependent(tarRoot, result)
callback()
})
} else {
recordIndependent(tarRoot, true)
callback()
}
}
// 为了获取资源的所属子包,该函数需串行执行
const processSubPackage = (subPackage, context, callback) => {
if (subPackage) {
if (typeof subPackage.root === 'string' && subPackage.root.startsWith('.')) {
emitError(`Current subpackage root [${subPackage.root}] is not allow starts with '.'`)
return callback()
}
const tarRoot = subPackage.tarRoot || subPackage.root || ''
const srcRoot = subPackage.srcRoot || subPackage.root || ''
if (!tarRoot) return callback()
context = path.join(context, srcRoot)
const otherConfig = getOtherConfig(subPackage)
subPackagesCfg[tarRoot] = subPackagesCfg[tarRoot] || {
root: tarRoot,
pages: []
}
async.parallel([
(callback) => {
processIndependent(otherConfig, context, tarRoot, callback)
},
(callback) => {
processPages(subPackage.pages, context, tarRoot, callback)
},
(callback) => {
processPlugins(subPackage.plugins, context, tarRoot, callback)
}
], (err) => {
if (err) return callback(err)
Object.assign(subPackagesCfg[tarRoot], otherConfig)
callback()
})
} else {
callback()
}
}
const processSubPackages = (subPackages, context, callback) => {
if (subPackages) {
async.each(subPackages, (subPackage, callback) => {
processSubPackage(subPackage, context, callback)
}, callback)
} else {
callback()
}
}
const wrapTabBarAsset = (expr) => {
if (mode !== 'ks') return expr
return `(function(p){return typeof p === "string" && p.charAt(0) === "/" ? p.slice(1) : p})(${expr})`
}
const processTabBar = (output) => {
const tabBarCfg = config[mode].tabBar
const itemKey = tabBarCfg.itemKey
const iconKey = tabBarCfg.iconKey
const activeIconKey = tabBarCfg.activeIconKey
if (json.tabBar && json.tabBar[itemKey]) {
json.tabBar[itemKey].forEach((item, index) => {
const iconPath = item[iconKey]
if (iconPath && isUrlRequest(iconPath)) {
const iconRequire = wrapTabBarAsset(`require("${addQuery(urlToRequest(iconPath), { useLocal: true })}")`)
output += `json.tabBar.${itemKey}[${index}].${iconKey} = ${iconRequire};\n`
}
const activeIconPath = item[activeIconKey]
if (activeIconPath && isUrlRequest(activeIconPath)) {
const activeIconRequire = wrapTabBarAsset(`require("${addQuery(urlToRequest(activeIconPath), { useLocal: true })}")`)
output += `json.tabBar.${itemKey}[${index}].${activeIconKey} = ${activeIconRequire};\n`
}
})
}
return output
}
const processOptionMenu = (output) => {
const optionMenuCfg = config[mode].optionMenu
if (optionMenuCfg && json.optionMenu) {
const iconKey = optionMenuCfg.iconKey
if (json.optionMenu[iconKey] && isUrlRequest(json.optionMenu[iconKey])) {
output += `json.optionMenu.${iconKey} = require("${addQuery(urlToRequest(json.optionMenu[iconKey]), { useLocal: true })}");\n`
}
}
return output
}
const processThemeLocation = (output) => {
if (json.themeLocation && isUrlRequest(json.themeLocation)) {
const requestString = getRequestString('json', { src: urlToRequest(json.themeLocation) }, {
isTheme: true,
isStatic: true
})
output += `json.themeLocation = require(${requestString});\n`
}
return output
}
const processWorkers = (workers, context, callback) => {
if (workers) {
const workersPath = path.join(context, workers)
this.addContextDependency(workersPath)
copydir(workersPath, context, callback)
} else {
callback()
}
}
const processCustomTabBar = (tabBar, context, callback) => {
const outputCustomKey = config[mode].tabBar.customKey
if (tabBar && tabBar[outputCustomKey]) {
const srcCustomKey = config[srcMode].tabBar.customKey
const srcPath = resolveTabBarPath(srcCustomKey)
const outputPath = resolveTabBarPath(outputCustomKey)
processComponent(`./${srcPath}`, context, {
outputPath,
extraOptions: {
replaceContent: 'true'
}
}, (err, entry) => {
if (err === RESOLVE_IGNORED_ERR) {
delete tabBar[srcCustomKey]
return callback()
}
if (err) return callback(err)
tabBar[outputCustomKey] = entry // hack for javascript parser call hook.
callback()
})
} else {
callback()
}
}
const processAppBar = (appBar, context, callback) => {
if (appBar) {
processComponent('./app-bar/index', context, {
outputPath: 'app-bar/index',
extraOptions: {
replaceContent: 'true'
}
}, (err, entry) => {
if (err === RESOLVE_IGNORED_ERR) {
return callback()
}
if (err) return callback(err)
appBar.custom = entry // hack for javascript parser call hook.
callback()
})
} else {
callback()
}
}
const processPluginGenericsImplementation = (plugin, context, tarRoot, callback) => {
if (!plugin.genericsImplementation) return callback()
const relativePath = useRelativePath ? publicPath + tarRoot : ''
async.eachOf(plugin.genericsImplementation, (genericComponents, name, callback) => {
async.eachOf(genericComponents, (genericComponentPath, name, callback) => {
processComponent(genericComponentPath, context, {
tarRoot,
relativePath
}, (err, entry) => {
if (err === RESOLVE_IGNORED_ERR) {
delete genericComponents[name]
return callback()
}
if (err) return callback(err)
genericComponents[name] = entry
callback()
})
}, callback)
}, callback)
}
const processPluginExport = (plugin, context, tarRoot, callback) => {
if (!plugin.export) return callback()
processJsExport(plugin.export, context, tarRoot, (err, entry) => {
if (err === RESOLVE_IGNORED_ERR) {
delete plugin.export
return callback()
}
if (err) return callback(err)
plugin.export = entry
callback()
})
}
const processPlugins = (plugins, context, tarRoot = '', callback) => {
if (mode !== 'wx' || !plugins) return callback() // 目前只有微信支持导出到插件
async.eachOf(plugins, (plugin, name, callback) => {
async.parallel([
(callback) => {
processPluginGenericsImplementation(plugin, context, tarRoot, callback)
},
(callback) => {
processPluginExport(plugin, context, tarRoot, callback)
}
], callback)
}, callback)
}
async.parallel([
(callback) => {
// 添加首页标识
if (json.pages && json.pages[0]) {
if (typeof json.pages[0] !== 'string') {
json.pages[0].src = addQuery(json.pages[0].src, { isFirst: true })
} else {
json.pages[0] = addQuery(json.pages[0], { isFirst: true })
}
}
processPages(json.pages, this.context, '', callback)
},
(callback) => {
processComponents(json.usingComponents, this.context, callback)
},
(callback) => {
processPlugins(json.plugins, this.context, '', callback)
},
(callback) => {
processWorkers(json.workers, this.context, callback)
},
(callback) => {
processPackages(json.packages, this.context, callback)
},
(callback) => {
processCustomTabBar(json.tabBar, this.context, callback)
},
(callback) => {
processSubPackages(json.subPackages || json.subpackages, this.context, callback)
},
(callback) => {
processAppBar(json.appBar, this.context, callback)
}
], (err) => {
if (err) return callback(err)
delete json.packages
delete json.subpackages
delete json.subPackages
json.pages = localPages
for (const root in subPackagesCfg) {
const subPackageCfg = subPackagesCfg[root]
// 分包不存在 pages,输出 subPackages 字段会报错
// tt模式下分包异步允许一个分包不存在 pages
if (subPackageCfg.pages.length || mode === 'tt') {
if (!json.subPackages) {
json.subPackages = []
}
json.subPackages.push(subPackageCfg)
}
}
const processOutput = (output) => {
output = processDynamicEntry(output)
output = processTabBar(output)
output = processOptionMenu(output)
output = processThemeLocation(output)
return output
}
callback(null, processOutput)
})
} else {
// page.json或component.json
const processGenerics = (generics, context, callback) => {
if (generics) {
async.eachOf(generics, (generic, name, callback) => {
if (generic.default) {
processComponent(generic.default, context, { relativePath }, (err, entry) => {
if (err === RESOLVE_IGNORED_ERR) {
delete generic.default
return callback()
}
if (err) return callback(err)
generic.default = entry
callback()
})
} else {
callback()
}
}, callback)
} else {
callback()
}
}
async.parallel([
(callback) => {
processComponents(json.usingComponents, this.context, callback)
},
(callback) => {
processGenerics(json.componentGenerics, this.context, callback)
}
], (err) => {
callback(err, processDynamicEntry)
})
}
}