-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
weapp.js
1952 lines (1891 loc) · 77.7 KB
/
weapp.js
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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const fs = require('fs-extra')
const os = require('os')
const path = require('path')
const chalk = require('chalk')
const chokidar = require('chokidar')
const wxTransformer = require('@tarojs/transformer-wx')
const babel = require('babel-core')
const traverse = require('babel-traverse').default
const t = require('babel-types')
const generate = require('babel-generator').default
const template = require('babel-template')
const autoprefixer = require('autoprefixer')
const postcss = require('postcss')
const pxtransform = require('postcss-pxtransform')
const cssUrlParse = require('postcss-url')
const minimatch = require('minimatch')
const _ = require('lodash')
const Util = require('./util')
const CONFIG = require('./config')
const npmProcess = require('./util/npm')
const { resolveNpmFilesPath, resolveNpmPkgMainPath } = require('./util/resolve_npm_files')
const babylonConfig = require('./config/babylon')
const browserList = require('./config/browser_list')
const defaultUglifyConfig = require('./config/uglify')
const defaultBabelConfig = require('./config/babel')
const astConvert = require('./util/ast_convert')
const appPath = process.cwd()
const configDir = path.join(appPath, Util.PROJECT_CONFIG)
const projectConfig = require(configDir)(_.merge)
const sourceDirName = projectConfig.sourceRoot || CONFIG.SOURCE_DIR
const outputDirName = projectConfig.outputRoot || CONFIG.OUTPUT_DIR
const sourceDir = path.join(appPath, sourceDirName)
const outputDir = path.join(appPath, outputDirName)
const entryFilePath = Util.resolveScriptPath(path.join(sourceDir, CONFIG.ENTRY))
const entryFileName = path.basename(entryFilePath)
const outputEntryFilePath = path.join(outputDir, entryFileName)
const pluginsConfig = projectConfig.plugins || {}
const weappConf = projectConfig.weapp || {}
const weappNpmConfig = Object.assign({
name: CONFIG.NPM_DIR,
dir: null
}, weappConf.npm)
const appOutput = typeof weappConf.appOutput === 'boolean' ? weappConf.appOutput : true
const notExistNpmList = []
const taroJsFramework = '@tarojs/taro'
const taroJsComponents = '@tarojs/components'
const taroJsRedux = '@tarojs/redux'
let appConfig = {}
const dependencyTree = {}
const depComponents = {}
const hasBeenBuiltComponents = []
const componentsBuildResult = {}
const componentsNamedMap = {}
const componentExportsMap = {}
const wxssDepTree = {}
let isBuildingScripts = {}
let isBuildingStyles = {}
let isCopyingFiles = {}
let isProduction = false
let buildAdapter = Util.BUILD_TYPES.WEAPP
let outputFilesTypes = Util.MINI_APP_FILES[buildAdapter]
let notTaroComponents = []
const NODE_MODULES = 'node_modules'
const NODE_MODULES_REG = /(.*)node_modules/
const nodeModulesPath = path.join(appPath, NODE_MODULES)
const PARSE_AST_TYPE = {
ENTRY: 'ENTRY',
PAGE: 'PAGE',
COMPONENT: 'COMPONENT',
NORMAL: 'NORMAL'
}
const DEVICE_RATIO = 'deviceRatio'
const isWindows = os.platform() === 'win32'
function getExactedNpmFilePath (npmName, filePath) {
try {
const npmInfo = resolveNpmFilesPath(npmName, isProduction, weappNpmConfig, buildAdapter)
const npmInfoMainPath = npmInfo.main
let outputNpmPath
if (Util.REG_STYLE.test(npmInfoMainPath)) {
outputNpmPath = npmInfoMainPath
} else {
if (!weappNpmConfig.dir) {
outputNpmPath = npmInfoMainPath.replace(NODE_MODULES, path.join(outputDirName, weappNpmConfig.name))
outputNpmPath = outputNpmPath.replace(/node_modules/g, weappNpmConfig.name)
} else {
const npmFilePath = npmInfoMainPath.replace(NODE_MODULES_REG, '')
outputNpmPath = path.join(path.resolve(configDir, '..', weappNpmConfig.dir), weappNpmConfig.name, npmFilePath)
}
}
const relativePath = path.relative(filePath, outputNpmPath)
return Util.promoteRelativePath(relativePath)
} catch (err) {
if (notExistNpmList.indexOf(npmName) < 0) {
notExistNpmList.push(npmName)
}
return npmName
}
}
function traverseObjectNode (node, obj) {
if (node.type === 'ClassProperty' || node.type === 'ObjectProperty') {
const properties = node.value.properties
obj = {}
properties.forEach(p => {
let key = t.isIdentifier(p.key) ? p.key.name : p.key.value
if (Util.CONFIG_MAP[buildAdapter][key]) {
key = Util.CONFIG_MAP[buildAdapter][key]
}
obj[key] = traverseObjectNode(p.value)
})
return obj
}
if (node.type === 'ObjectExpression') {
const properties = node.properties
obj = {}
properties.forEach(p => {
let key = t.isIdentifier(p.key) ? p.key.name : p.key.value
if (Util.CONFIG_MAP[buildAdapter][key]) {
key = Util.CONFIG_MAP[buildAdapter][key]
}
obj[key] = traverseObjectNode(p.value)
})
return obj
}
if (node.type === 'ArrayExpression') {
return node.elements.map(item => traverseObjectNode(item))
}
if (node.type === 'NullLiteral') {
return null
}
return node.value
}
function analyzeImportUrl ({ astPath, value, depComponents, sourceFilePath, filePath, styleFiles, scriptFiles, jsonFiles, mediaFiles }) {
const valueExtname = path.extname(value)
const node = astPath.node
if (value.indexOf('.') === 0) {
let importPath = path.resolve(path.dirname(sourceFilePath), value)
importPath = Util.resolveScriptPath(importPath)
if (isFileToBePage(importPath)) {
astPath.remove()
} else {
if (Util.REG_SCRIPT.test(valueExtname) || Util.REG_TYPESCRIPT.test(valueExtname)) {
const vpath = path.resolve(sourceFilePath, '..', value)
let fPath = value
if (fs.existsSync(vpath) && !NODE_MODULES_REG.test(vpath)) {
fPath = vpath
}
if (scriptFiles.indexOf(fPath) < 0) {
scriptFiles.push(fPath)
}
} else if (Util.REG_JSON.test(valueExtname)) {
const vpath = path.resolve(sourceFilePath, '..', value)
if (jsonFiles.indexOf(vpath) < 0) {
jsonFiles.push(vpath)
}
if (fs.existsSync(vpath)) {
const obj = JSON.parse(fs.readFileSync(vpath).toString())
const specifiers = node.specifiers
let defaultSpecifier = null
specifiers.forEach(item => {
if (item.type === 'ImportDefaultSpecifier') {
defaultSpecifier = item.local.name
}
})
if (defaultSpecifier) {
let objArr = [t.nullLiteral()]
if (Array.isArray(obj)) {
objArr = t.arrayExpression(astConvert.array(obj))
} else {
objArr = t.objectExpression(astConvert.obj(obj))
}
astPath.replaceWith(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(defaultSpecifier), objArr)]))
}
}
} else if (Util.REG_FONT.test(valueExtname) || Util.REG_IMAGE.test(valueExtname) || Util.REG_MEDIA.test(valueExtname)) {
const vpath = path.resolve(sourceFilePath, '..', value)
if (!fs.existsSync(vpath)) {
Util.printLog(Util.pocessTypeEnum.ERROR, '引用文件', `文件 ${sourceFilePath} 中引用 ${value} 不存在!`)
return
}
if (mediaFiles.indexOf(vpath) < 0) {
mediaFiles.push(vpath)
}
const specifiers = node.specifiers
let defaultSpecifier = null
specifiers.forEach(item => {
if (item.type === 'ImportDefaultSpecifier') {
defaultSpecifier = item.local.name
}
})
let sourceDirPath = sourceDir
if (NODE_MODULES_REG.test(vpath)) {
sourceDirPath = nodeModulesPath
}
if (defaultSpecifier) {
if (buildAdapter === Util.BUILD_TYPES.SWAN) {
astPath.replaceWith(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(defaultSpecifier), t.stringLiteral(Util.promoteRelativePath(path.relative(sourceFilePath, vpath)).replace(/\\/g, '/')))]))
} else {
astPath.replaceWith(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(defaultSpecifier), t.stringLiteral(vpath.replace(sourceDirPath, '').replace(/\\/g, '/')))]))
}
} else {
astPath.remove()
}
} else if (Util.REG_STYLE.test(valueExtname)) {
const stylePath = path.resolve(path.dirname(sourceFilePath), value)
if (styleFiles.indexOf(stylePath) < 0) {
styleFiles.push(stylePath)
}
astPath.remove()
} else {
let vpath = Util.resolveScriptPath(path.resolve(sourceFilePath, '..', value))
let outputVpath
if (NODE_MODULES_REG.test(vpath)) {
outputVpath = vpath.replace(nodeModulesPath, path.join(outputDir, weappNpmConfig.name))
} else {
outputVpath = vpath.replace(sourceDir, outputDir)
}
let relativePath = path.relative(filePath, outputVpath)
if (vpath && vpath !== sourceFilePath) {
if (!fs.existsSync(vpath)) {
Util.printLog(Util.pocessTypeEnum.ERROR, '引用文件', `文件 ${sourceFilePath} 中引用 ${value} 不存在!`)
} else {
if (fs.lstatSync(vpath).isDirectory()) {
if (fs.existsSync(path.join(vpath, 'index.js'))) {
vpath = path.join(vpath, 'index.js')
relativePath = path.join(relativePath, 'index.js')
} else {
Util.printLog(Util.pocessTypeEnum.ERROR, '引用目录', `文件 ${sourceFilePath} 中引用了目录 ${value}!`)
return
}
}
if (scriptFiles.indexOf(vpath) < 0) {
scriptFiles.push(vpath)
}
relativePath = Util.promoteRelativePath(relativePath)
relativePath = relativePath.replace(path.extname(relativePath), '.js')
node.source.value = relativePath
}
}
}
}
}
}
function parseAst (type, ast, depComponents, sourceFilePath, filePath, npmSkip = false) {
const styleFiles = []
const scriptFiles = []
const jsonFiles = []
const mediaFiles = []
let configObj = {}
let componentClassName = null
let taroJsReduxConnect = null
let taroMiniAppFramework = `@tarojs/taro-${buildAdapter}`
let taroImportDefaultName
let needExportDefault = false
let exportTaroReduxConnected = null
const constantsReplaceList = Object.assign({
'process.env.TARO_ENV': buildAdapter
}, Util.generateEnvList(projectConfig.env || {}), Util.generateConstantsList(projectConfig.defineConstants || {}))
ast = babel.transformFromAst(ast, '', {
plugins: [
[require('babel-plugin-danger-remove-unused-import'), { ignore: ['@tarojs/taro', 'react', 'nervjs'] }],
[require('babel-plugin-transform-define').default, constantsReplaceList]
]
}).ast
traverse(ast, {
ClassDeclaration (astPath) {
const node = astPath.node
let hasCreateData = false
if (node.superClass) {
astPath.traverse({
ClassMethod (astPath) {
if (astPath.get('key').isIdentifier({ name: '_createData' })) {
hasCreateData = true
}
}
})
if (hasCreateData) {
needExportDefault = true
astPath.traverse({
ClassMethod (astPath) {
const node = astPath.node
if (node.kind === 'constructor') {
astPath.traverse({
ExpressionStatement (astPath) {
const node = astPath.node
if (node.expression &&
node.expression.type === 'AssignmentExpression' &&
node.expression.operator === '=') {
const left = node.expression.left
if (left.type === 'MemberExpression' &&
left.object.type === 'ThisExpression' &&
left.property.type === 'Identifier' &&
left.property.name === 'config') {
configObj = traverseObjectNode(node.expression.right)
}
}
}
})
}
}
})
if (node.id === null) {
componentClassName = '_TaroComponentClass'
astPath.replaceWith(t.classDeclaration(t.identifier(componentClassName), node.superClass, node.body, node.decorators || []))
} else if (node.id.name === 'App') {
componentClassName = '_App'
astPath.replaceWith(t.classDeclaration(t.identifier(componentClassName), node.superClass, node.body, node.decorators || []))
} else {
componentClassName = node.id.name
}
}
}
},
ClassExpression (astPath) {
const node = astPath.node
if (node.superClass) {
let hasCreateData = false
astPath.traverse({
ClassMethod (astPath) {
if (astPath.get('key').isIdentifier({ name: '_createData' })) {
hasCreateData = true
}
}
})
if (hasCreateData) {
needExportDefault = true
if (node.id === null) {
const parentNode = astPath.parentPath.node
if (t.isVariableDeclarator(astPath.parentPath)) {
componentClassName = parentNode.id.name
} else {
componentClassName = '_TaroComponentClass'
}
astPath.replaceWith(t.ClassExpression(t.identifier(componentClassName), node.superClass, node.body, node.decorators || []))
} else if (node.id.name === 'App') {
componentClassName = '_App'
astPath.replaceWith(t.ClassExpression(t.identifier(componentClassName), node.superClass, node.body, node.decorators || []))
} else {
componentClassName = node.id.name
}
}
}
},
ClassProperty (astPath) {
const node = astPath.node
if (node.key.name === 'config') {
configObj = traverseObjectNode(node)
}
},
ImportDeclaration (astPath) {
const node = astPath.node
const source = node.source
let value = source.value
if (Util.isNpmPkg(value) && notExistNpmList.indexOf(value) < 0) {
if (value === taroJsComponents) {
astPath.remove()
} else {
let isDepComponent = false
if (depComponents && depComponents.length) {
depComponents.forEach(item => {
if (item.path === value) {
isDepComponent = true
}
})
}
if (isDepComponent) {
astPath.remove()
} else {
const specifiers = node.specifiers
if (value === taroJsFramework) {
let defaultSpecifier = null
specifiers.forEach(item => {
if (item.type === 'ImportDefaultSpecifier') {
defaultSpecifier = item.local.name
}
})
if (defaultSpecifier) {
taroImportDefaultName = defaultSpecifier
}
value = taroMiniAppFramework
} else if (value === taroJsRedux) {
specifiers.forEach(item => {
if (item.type === 'ImportSpecifier') {
const local = item.local
if (local.type === 'Identifier' && local.name === 'connect') {
taroJsReduxConnect = item.imported.name
}
}
})
}
if (!npmSkip) {
source.value = getExactedNpmFilePath(value, filePath)
} else {
source.value = value
}
}
}
} else if (path.isAbsolute(value)) {
Util.printLog(Util.pocessTypeEnum.ERROR, '引用文件', `文件 ${sourceFilePath} 中引用 ${value} 是绝对路径!`)
}
},
CallExpression (astPath) {
const node = astPath.node
const callee = node.callee
if (t.isMemberExpression(callee)) {
if (taroImportDefaultName && callee.object.name === taroImportDefaultName && callee.property.name === 'render') {
astPath.remove()
}
} else if (callee.name === 'require') {
const args = node.arguments
let value = args[0].value
if (Util.isNpmPkg(value) && notExistNpmList.indexOf(value) < 0) {
if (value === taroJsComponents) {
astPath.remove()
} else {
let isDepComponent = false
if (depComponents && depComponents.length) {
depComponents.forEach(item => {
if (item.path === value) {
isDepComponent = true
}
})
}
if (isDepComponent) {
astPath.remove()
} else {
if (t.isVariableDeclaration(astPath.parentPath.parentPath)) {
const parentNode = astPath.parentPath.parentPath.node
if (parentNode.declarations.length === 1 && parentNode.declarations[0].init) {
const id = parentNode.declarations[0].id
if (value === taroJsFramework && id.type === 'Identifier') {
taroImportDefaultName = id.name
value = taroMiniAppFramework
} else if (value === taroJsRedux) {
const declarations = parentNode.declarations
declarations.forEach(item => {
const id = item.id
if (id.type === 'ObjectPattern') {
const properties = id.properties
properties.forEach(p => {
if (p.type === 'ObjectProperty') {
if (p.value.type === 'Identifier' && p.value.name === 'connect') {
taroJsReduxConnect = p.key.name
}
}
})
}
})
}
}
}
if (!npmSkip) {
args[0].value = getExactedNpmFilePath(value, filePath)
} else {
args[0].value = value
}
}
}
}
if (path.isAbsolute(value)) {
Util.printLog(Util.pocessTypeEnum.ERROR, '引用文件', `文件 ${sourceFilePath} 中引用 ${value} 是绝对路径!`)
}
}
},
ExportDefaultDeclaration (astPath) {
const node = astPath.node
const declaration = node.declaration
needExportDefault = false
if (
declaration &&
(declaration.type === 'ClassDeclaration' || declaration.type === 'ClassExpression')
) {
const superClass = declaration.superClass
if (superClass) {
let hasCreateData = false
astPath.traverse({
ClassMethod (astPath) {
if (astPath.get('key').isIdentifier({ name: '_createData' })) {
hasCreateData = true
}
}
})
if (hasCreateData) {
needExportDefault = true
if (declaration.id === null) {
componentClassName = '_TaroComponentClass'
} else if (declaration.id.name === 'App') {
componentClassName = '_App'
} else {
componentClassName = declaration.id.name
}
const isClassDcl = declaration.type === 'ClassDeclaration'
const classDclProps = [t.identifier(componentClassName), superClass, declaration.body, declaration.decorators || []]
astPath.replaceWith(isClassDcl ? t.classDeclaration.apply(null, classDclProps) : t.classExpression.apply(null, classDclProps))
}
}
} else if (declaration.type === 'CallExpression') {
const callee = declaration.callee
if (callee && callee.type === 'CallExpression') {
const subCallee = callee.callee
if (subCallee.type === 'Identifier' && subCallee.name === taroJsReduxConnect) {
const args = declaration.arguments
if (args.length === 1 && args[0].name === componentClassName) {
needExportDefault = true
exportTaroReduxConnected = `${componentClassName}__Connected`
astPath.replaceWith(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(`${componentClassName}__Connected`), t.CallExpression(declaration.callee, declaration.arguments))]))
}
}
}
}
},
ExportNamedDeclaration (astPath) {
const node = astPath.node
const source = node.source
if (source && source.type === 'StringLiteral') {
const value = source.value
analyzeImportUrl({ astPath, value, depComponents, sourceFilePath, filePath, styleFiles, scriptFiles, jsonFiles, mediaFiles })
}
},
ExportAllDeclaration (astPath) {
const node = astPath.node
const source = node.source
if (source && source.type === 'StringLiteral') {
const value = source.value
analyzeImportUrl({ astPath, value, depComponents, sourceFilePath, filePath, styleFiles, scriptFiles, jsonFiles, mediaFiles })
}
},
Program: {
exit (astPath) {
astPath.traverse({
ImportDeclaration (astPath) {
const node = astPath.node
const source = node.source
let value = source.value
analyzeImportUrl({ astPath, value, depComponents, sourceFilePath, filePath, styleFiles, scriptFiles, jsonFiles, mediaFiles })
},
CallExpression (astPath) {
const node = astPath.node
const callee = node.callee
if (callee.name === 'require') {
const args = node.arguments
let value = args[0].value
const valueExtname = path.extname(value)
if (value.indexOf('.') === 0) {
let importPath = path.resolve(path.dirname(sourceFilePath), value)
importPath = Util.resolveScriptPath(importPath)
if (isFileToBePage(importPath)) {
if (astPath.parent.type === 'AssignmentExpression' || 'ExpressionStatement') {
astPath.parentPath.remove()
} else if (astPath.parent.type === 'VariableDeclarator') {
astPath.parentPath.parentPath.remove()
} else {
astPath.remove()
}
} else {
if (Util.REG_STYLE.test(valueExtname)) {
const stylePath = path.resolve(path.dirname(sourceFilePath), value)
if (styleFiles.indexOf(stylePath) < 0) {
styleFiles.push(stylePath)
}
if (astPath.parent.type === 'AssignmentExpression' || 'ExpressionStatement') {
astPath.parentPath.remove()
} else if (astPath.parent.type === 'VariableDeclarator') {
astPath.parentPath.parentPath.remove()
} else {
astPath.remove()
}
} else if (Util.REG_JSON.test(valueExtname)) {
const vpath = path.resolve(sourceFilePath, '..', value)
if (jsonFiles.indexOf(vpath) < 0) {
jsonFiles.push(vpath)
}
if (fs.existsSync(vpath)) {
const obj = JSON.parse(fs.readFileSync(vpath).toString())
let objArr = [t.nullLiteral()]
if (Array.isArray(obj)) {
objArr = t.arrayExpression(astConvert.array(obj))
} else {
objArr = t.objectExpression(astConvert.obj(obj))
}
astPath.replaceWith(t.objectExpression(objArr))
}
} else if (Util.REG_SCRIPT.test(valueExtname) || Util.REG_TYPESCRIPT.test(valueExtname)) {
const vpath = path.resolve(sourceFilePath, '..', value)
let fPath = value
if (fs.existsSync(vpath) && !NODE_MODULES_REG.test(vpath)) {
fPath = vpath
}
if (scriptFiles.indexOf(fPath) < 0) {
scriptFiles.push(fPath)
}
} else if (Util.REG_FONT.test(valueExtname) || Util.REG_IMAGE.test(valueExtname) || Util.REG_MEDIA.test(valueExtname)) {
const vpath = path.resolve(sourceFilePath, '..', value)
if (mediaFiles.indexOf(vpath) < 0) {
mediaFiles.push(vpath)
}
let sourceDirPath = sourceDir
if (NODE_MODULES_REG.test(vpath)) {
sourceDirPath = nodeModulesPath
}
if (buildAdapter === Util.BUILD_TYPES.SWAN) {
astPath.replaceWith(t.stringLiteral(Util.promoteRelativePath(path.relative(sourceFilePath, vpath)).replace(/\\/g, '/')))
} else {
astPath.replaceWith(t.stringLiteral(vpath.replace(sourceDirPath, '').replace(/\\/g, '/')))
}
} else {
let vpath = Util.resolveScriptPath(path.resolve(sourceFilePath, '..', value))
let outputVpath
if (NODE_MODULES_REG.test(vpath)) {
outputVpath = vpath.replace(nodeModulesPath, path.join(outputDir, weappNpmConfig.name))
} else {
outputVpath = vpath.replace(sourceDir, outputDir)
}
let relativePath = path.relative(filePath, outputVpath)
if (vpath) {
if (!fs.existsSync(vpath)) {
Util.printLog(Util.pocessTypeEnum.ERROR, '引用文件', `文件 ${sourceFilePath} 中引用 ${value} 不存在!`)
} else {
if (fs.lstatSync(vpath).isDirectory()) {
if (fs.existsSync(path.join(vpath, 'index.js'))) {
vpath = path.join(vpath, 'index.js')
relativePath = path.join(relativePath, 'index.js')
} else {
Util.printLog(Util.pocessTypeEnum.ERROR, '引用目录', `文件 ${sourceFilePath} 中引用了目录 ${value}!`)
return
}
}
if (scriptFiles.indexOf(vpath) < 0) {
scriptFiles.push(vpath)
}
relativePath = Util.promoteRelativePath(relativePath)
relativePath = relativePath.replace(path.extname(relativePath), '.js')
args[0].value = relativePath
}
}
}
}
}
}
}
})
const node = astPath.node
const exportVariableName = exportTaroReduxConnected || componentClassName
if (needExportDefault) {
const exportDefault = template(`export default ${exportVariableName}`, babylonConfig)()
node.body.push(exportDefault)
}
const taroMiniAppFrameworkPath = !npmSkip ? getExactedNpmFilePath(taroMiniAppFramework, filePath) : taroMiniAppFramework
switch (type) {
case PARSE_AST_TYPE.ENTRY:
const pxTransformConfig = {
designWidth: projectConfig.designWidth || 750
}
if (projectConfig.hasOwnProperty(DEVICE_RATIO)) {
pxTransformConfig[DEVICE_RATIO] = projectConfig.deviceRatio
}
node.body.push(template(`App(require('${taroMiniAppFrameworkPath}').default.createApp(${exportVariableName}))`, babylonConfig)())
node.body.push(template(`Taro.initPxTransform(${JSON.stringify(pxTransformConfig)})`, babylonConfig)())
break
case PARSE_AST_TYPE.PAGE:
if (buildAdapter === Util.BUILD_TYPES.WEAPP) {
node.body.push(template(`Component(require('${taroMiniAppFrameworkPath}').default.createComponent(${exportVariableName}, true))`, babylonConfig)())
} else {
node.body.push(template(`Page(require('${taroMiniAppFrameworkPath}').default.createComponent(${exportVariableName}, true))`, babylonConfig)())
}
break
case PARSE_AST_TYPE.COMPONENT:
node.body.push(template(`Component(require('${taroMiniAppFrameworkPath}').default.createComponent(${exportVariableName}))`, babylonConfig)())
break
default:
break
}
}
}
})
return {
code: generate(ast).code,
styleFiles,
scriptFiles,
jsonFiles,
configObj,
mediaFiles,
componentClassName
}
}
function parseComponentExportAst (ast, componentName, componentPath, componentType) {
let componentRealPath = null
let importExportName
const constantsReplaceList = Object.assign({
'process.env.TARO_ENV': buildAdapter
}, Util.generateEnvList(projectConfig.env || {}), Util.generateConstantsList(projectConfig.defineConstants || {}))
ast = babel.transformFromAst(ast, '', {
plugins: [
[require('babel-plugin-transform-define').default, constantsReplaceList]
]
}).ast
traverse(ast, {
ExportNamedDeclaration (astPath) {
const node = astPath.node
const specifiers = node.specifiers
const source = node.source
if (source && source.type === 'StringLiteral') {
specifiers.forEach(specifier => {
const exported = specifier.exported
if (_.kebabCase(exported.name) === componentName) {
componentRealPath = Util.resolveScriptPath(path.resolve(path.dirname(componentPath), source.value))
}
})
} else {
specifiers.forEach(specifier => {
const exported = specifier.exported
if (_.kebabCase(exported.name) === componentName) {
importExportName = exported.name
}
})
}
},
ExportDefaultDeclaration (astPath) {
const node = astPath.node
const declaration = node.declaration
if (componentType === 'default') {
importExportName = declaration.name
}
},
CallExpression (astPath) {
if (astPath.get('callee').isIdentifier({ name: 'require' })) {
const arg = astPath.get('arguments')[0]
if (t.isStringLiteral(arg.node)) {
componentRealPath = Util.resolveScriptPath(path.resolve(path.dirname(componentPath), arg.node.value))
}
}
},
Program: {
exit (astPath) {
astPath.traverse({
ImportDeclaration (astPath) {
const node = astPath.node
const specifiers = node.specifiers
const source = node.source
if (importExportName) {
specifiers.forEach(specifier => {
const local = specifier.local
if (local.name === importExportName) {
componentRealPath = Util.resolveScriptPath(path.resolve(path.dirname(componentPath), source.value))
}
})
}
}
})
}
}
})
return componentRealPath
}
function isFileToBeTaroComponent (code, sourcePath, outputPath) {
const transformResult = wxTransformer({
code,
sourcePath: sourcePath,
outputPath: outputPath,
isNormal: true,
isTyped: Util.REG_TYPESCRIPT.test(sourcePath),
adapter: buildAdapter
})
const { ast } = transformResult
let isTaroComponent = false
traverse(ast, {
ClassDeclaration (astPath) {
astPath.traverse({
ClassMethod (astPath) {
if (astPath.get('key').isIdentifier({ name: 'render' })) {
astPath.traverse({
JSXElement () {
isTaroComponent = true
}
})
}
}
})
},
ClassExpression (astPath) {
astPath.traverse({
ClassMethod (astPath) {
if (astPath.get('key').isIdentifier({ name: 'render' })) {
astPath.traverse({
JSXElement () {
isTaroComponent = true
}
})
}
}
})
}
})
return {
isTaroComponent,
transformResult
}
}
function isFileToBePage (filePath) {
let isPage = false
const extname = path.extname(filePath)
const pages = appConfig.pages || []
const filePathWithoutExt = filePath.replace(extname, '')
pages.forEach(page => {
if (filePathWithoutExt === path.join(sourceDir, page)) {
isPage = true
}
})
return isPage && Util.REG_SCRIPTS.test(extname)
}
function copyFilesFromSrcToOutput (files) {
files.forEach(file => {
let outputFilePath
if (NODE_MODULES_REG.test(file)) {
outputFilePath = file.replace(nodeModulesPath, path.join(outputDir, weappNpmConfig.name))
} else {
outputFilePath = file.replace(sourceDir, outputDir)
}
if (isCopyingFiles[outputFilePath]) {
return
}
isCopyingFiles[outputFilePath] = true
let modifySrc = file.replace(appPath + path.sep, '')
modifySrc = modifySrc.split(path.sep).join('/')
let modifyOutput = outputFilePath.replace(appPath + path.sep, '')
modifyOutput = modifyOutput.split(path.sep).join('/')
Util.printLog(Util.pocessTypeEnum.COPY, '文件', modifyOutput)
if (!fs.existsSync(file)) {
Util.printLog(Util.pocessTypeEnum.ERROR, '文件', `${modifySrc} 不存在`)
} else {
fs.ensureDir(path.dirname(outputFilePath))
fs.copySync(file, outputFilePath)
}
})
}
const babelConfig = _.mergeWith(defaultBabelConfig, pluginsConfig.babel, (objValue, srcValue) => {
if (Array.isArray(objValue)) {
return Array.from(new Set(objValue.concat(srcValue)))
}
})
const shouldTransformAgain = (function () {
const pluginsStr = JSON.stringify(babelConfig.plugins)
if (/transform-runtime/.test(pluginsStr)) {
return true
}
return false
})()
async function compileScriptFile (content, sourceFilePath, outputFilePath, adapter) {
const compileScriptRes = await npmProcess.callPlugin('babel', content, entryFilePath, babelConfig)
const code = compileScriptRes.code
if (!shouldTransformAgain) {
return code
}
const transformResult = wxTransformer({
code,
sourcePath: sourceFilePath,
outputPath: outputFilePath,
isNormal: true,
isTyped: false,
adapter
})
const res = parseAst(PARSE_AST_TYPE.NORMAL, transformResult.ast, [], sourceFilePath, outputFilePath)
return res.code
}
function buildProjectConfig () {
let projectConfigFileName = ''
if (buildAdapter === Util.BUILD_TYPES.WEAPP) {
projectConfigFileName = 'project.config.json'
const projectConfigPath = path.join(appPath, projectConfigFileName)
if (!fs.existsSync(projectConfigPath)) {
return
}
const origProjectConfig = fs.readJSONSync(projectConfigPath)
fs.ensureDirSync(outputDir)
fs.writeFileSync(
path.join(outputDir, projectConfigFileName),
JSON.stringify(Object.assign({}, origProjectConfig, { miniprogramRoot: './' }), null, 2)
)
} else if (buildAdapter === Util.BUILD_TYPES.SWAN) {
projectConfigFileName = 'project.swan.json'
const projectConfigObj = {
appid: 'testappid',
setting: {
urlCheck: false
}
}
fs.ensureDirSync(outputDir)
fs.writeFileSync(
path.join(outputDir, projectConfigFileName),
JSON.stringify(projectConfigObj, null, 2)
)
}
Util.printLog(Util.pocessTypeEnum.GENERATE, '工具配置', `${outputDirName}/${projectConfigFileName}`)
}
function buildWorkers (worker) {
Util.printLog(Util.pocessTypeEnum.COMPILE, 'Workers', '编译 worker 相关文件')
const workerDir = path.join(sourceDir, worker)
function fileRecursiveSearch (fileDir) {
fs.readdir(fileDir, (err, files) => {
if (err) {
console.warn(err)
} else {
files.forEach(filename => {
const filePath = path.join(fileDir, filename)
fs.stat(filePath, (err, stats) => {
if (err) {
console.warn(err)
} else {
const isFile = stats.isFile()
const isDir = stats.isDirectory()
if (isFile) {
if (Util.REG_SCRIPTS.test(filePath)) {
compileDepScripts([filePath])
} else {
copyFilesFromSrcToOutput([filePath])
}
} else if (isDir) {
fileRecursiveSearch(filePath)
}
}
})
})
}
})
}
fileRecursiveSearch(workerDir)
}
async function buildEntry () {
Util.printLog(Util.pocessTypeEnum.COMPILE, '入口文件', `${sourceDirName}/${entryFileName}`)
const entryFileCode = fs.readFileSync(entryFilePath).toString()
try {
const transformResult = wxTransformer({
code: entryFileCode,
sourcePath: entryFilePath,
outputPath: outputEntryFilePath,
isApp: true,
isTyped: Util.REG_TYPESCRIPT.test(entryFilePath),
adapter: buildAdapter
})
// app.js的template忽略
const res = parseAst(PARSE_AST_TYPE.ENTRY, transformResult.ast, [], entryFilePath, outputEntryFilePath)
let resCode = res.code
resCode = await compileScriptFile(resCode, entryFilePath, outputEntryFilePath, buildAdapter)
if (isProduction) {
const uglifyPluginConfig = pluginsConfig.uglify || { enable: true }
if (uglifyPluginConfig.enable) {
const uglifyConfig = Object.assign(defaultUglifyConfig, uglifyPluginConfig.config || {})
const uglifyResult = npmProcess.callPluginSync('uglifyjs', resCode, entryFilePath, uglifyConfig)
if (uglifyResult.error) {
Util.printLog(Util.pocessTypeEnum.ERROR, '压缩错误', `文件${entryFilePath}`)
console.log(uglifyResult.error)
} else {
resCode = uglifyResult.code
}
}
}
if (appOutput) {
fs.writeFileSync(path.join(outputDir, 'app.json'), JSON.stringify(res.configObj, null, 2))
Util.printLog(Util.pocessTypeEnum.GENERATE, '入口配置', `${outputDirName}/app.json`)
fs.writeFileSync(path.join(outputDir, 'app.js'), resCode)
Util.printLog(Util.pocessTypeEnum.GENERATE, '入口文件', `${outputDirName}/app.js`)
}
if (res.configObj.workers) {