@mpxjs/webpack-plugin 2.8.63 → 2.8.64-bridgetest

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -24,8 +24,9 @@ function objectKeys (obj) {
24
24
  var shift = false
25
25
  for (var i = 1; i < objStr.length - 1; i++) {
26
26
  var item = objStr[i]
27
+ var lastItem = objStr[i - 1]
27
28
  if (inKey) {
28
- if (item === ':') {
29
+ if (item === ':' && lastItem === '"') {
29
30
  keys.push(key.slice(1, -1))
30
31
  key = ''
31
32
  inKey = false
@@ -93,18 +94,53 @@ function isDef (v) {
93
94
  return v !== undefined && v !== null
94
95
  }
95
96
 
97
+ var escapeMap = {
98
+ '(': '_pl_',
99
+ ')': '_pr_',
100
+ '[': '_bl_',
101
+ ']': '_br_',
102
+ '{': '_cl_',
103
+ '#': '_h_',
104
+ '!': '_i_',
105
+ '/': '_s_',
106
+ '.': '_d_',
107
+ ':': '_c_',
108
+ ',': '_2c_',
109
+ '%': '_p_',
110
+ // wxs can not use '\'' as key
111
+ // wxs环境中'\''!=="'",此文件不能格式化,否则会导致程序错误
112
+ "'": '_q_',
113
+ // wxs can not use '"' as key
114
+ '"': '_dq_',
115
+ '+': '_a_',
116
+ '$': '_si_'
117
+ }
118
+
119
+ var escapeReg = genRegExp('[()[\]{}#!/.:,%\'"+$]', 'g')
120
+
121
+ function mpEscape (str) {
122
+ return str.replace(escapeReg, function (match) {
123
+ if (escapeMap[match]) return escapeMap[match]
124
+ // fix wxs can not use '}' as key
125
+ if (match === '}') return '_cr_'
126
+ // unknown escaped
127
+ return '_u_'
128
+ })
129
+ }
130
+
131
+
96
132
  function stringifyDynamicClass (value) {
97
- if (!value) return ''
98
133
  if (isArray(value)) {
99
- return stringifyArray(value)
100
- }
101
- if (isObject(value)) {
102
- return stringifyObject(value)
134
+ value = stringifyArray(value)
135
+ } else if (isObject(value)) {
136
+ value = stringifyObject(value)
103
137
  }
138
+
104
139
  if (typeof value === 'string') {
105
- return value
140
+ return mpEscape(value)
141
+ } else {
142
+ return ''
106
143
  }
107
- return ''
108
144
  }
109
145
 
110
146
  function stringifyArray (value) {
@@ -738,7 +738,7 @@ function parse (template, options) {
738
738
  },
739
739
  comment: function comment (text) {
740
740
  if (!currentParent) genTempRoot()
741
- if (options.hasComment) {
741
+ if (options.hasComment || /mpx_config_/.test(text)) {
742
742
  currentParent.children.push({
743
743
  type: 3,
744
744
  text: text,
@@ -944,7 +944,7 @@ function processComponentIs (el, options) {
944
944
 
945
945
  const is = getAndRemoveAttr(el, 'is').val
946
946
  if (is) {
947
- el.is = parseMustache(is).result
947
+ el.is = parseMustacheWithContext(is).result
948
948
  } else {
949
949
  warn$1('<component> tag should have attrs[is].')
950
950
  }
@@ -956,7 +956,7 @@ function parseFuncStr2 (str) {
956
956
  const funcRE = /^([^()]+)(\((.*)\))?/
957
957
  const match = funcRE.exec(str)
958
958
  if (match) {
959
- const funcName = parseMustache(match[1]).result
959
+ const funcName = parseMustacheWithContext(match[1]).result
960
960
  const hasArgs = !!match[2]
961
961
  let args = match[3] ? `,${match[3]}` : ''
962
962
  const ret = /(,|^)\s*(\$event)\s*(,|$)/.exec(args)
@@ -1142,19 +1142,9 @@ function wrapMustache (val) {
1142
1142
  return val && !tagRE.test(val) ? `{{${val}}}` : val
1143
1143
  }
1144
1144
 
1145
- function parseMustache (raw = '') {
1146
- let replaced = false
1147
- if (tagRE.test(raw)) {
1148
- const ret = []
1149
- let lastLastIndex = 0
1150
- let match
1151
- while (match = tagREG.exec(raw)) {
1152
- const pre = raw.substring(lastLastIndex, match.index)
1153
- if (pre) {
1154
- ret.push(stringify(pre))
1155
- }
1156
- let exp = match[1]
1157
-
1145
+ function parseMustacheWithContext (raw = '') {
1146
+ return parseMustache(raw, (exp) => {
1147
+ if (defs) {
1158
1148
  // eval处理的话,和别的判断条件,比如运行时的判断混用情况下得不到一个结果,还是正则替换
1159
1149
  const defKeys = Object.keys(defs)
1160
1150
  defKeys.forEach((defKey) => {
@@ -1162,42 +1152,70 @@ function parseMustache (raw = '') {
1162
1152
  const defREG = new RegExp(`\\b${defKey}\\b`, 'g')
1163
1153
  if (defRE.test(exp)) {
1164
1154
  exp = exp.replace(defREG, stringify(defs[defKey]))
1165
- replaced = true
1166
1155
  }
1167
1156
  })
1157
+ }
1168
1158
 
1169
- if (i18n) {
1170
- for (const i18nFuncName of i18nFuncNames) {
1171
- const funcNameRE = new RegExp(`(?<![A-Za-z0-9_$.])${i18nFuncName}\\(`)
1172
- const funcNameREG = new RegExp(`(?<![A-Za-z0-9_$.])${i18nFuncName}\\(`, 'g')
1173
- if (funcNameRE.test(exp)) {
1174
- if (i18n.useComputed || !i18nFuncName.startsWith('\\$')) {
1175
- const i18nInjectComputedKey = `_i${i18nInjectableComputed.length + 1}`
1176
- i18nInjectableComputed.push(`${i18nInjectComputedKey} () {\nreturn ${exp.trim()}}`)
1177
- exp = i18nInjectComputedKey
1178
- } else {
1179
- exp = exp.replace(funcNameREG, `${i18nModuleName}.$1(null, _l, _fl, `)
1180
- }
1181
- hasI18n = true
1182
- replaced = true
1183
- break
1159
+ if (i18n) {
1160
+ for (const i18nFuncName of i18nFuncNames) {
1161
+ const funcNameRE = new RegExp(`(?<![A-Za-z0-9_$.])${i18nFuncName}\\(`)
1162
+ const funcNameREG = new RegExp(`(?<![A-Za-z0-9_$.])${i18nFuncName}\\(`, 'g')
1163
+ if (funcNameRE.test(exp)) {
1164
+ if (i18n.useComputed || !i18nFuncName.startsWith('\\$')) {
1165
+ const i18nInjectComputedKey = `_i${i18nInjectableComputed.length + 1}`
1166
+ i18nInjectableComputed.push(`${i18nInjectComputedKey} () {\nreturn ${exp.trim()}}`)
1167
+ exp = i18nInjectComputedKey
1168
+ } else {
1169
+ exp = exp.replace(funcNameREG, `${i18nModuleName}.$1(null, _l, _fl, `)
1184
1170
  }
1171
+ hasI18n = true
1172
+ break
1185
1173
  }
1186
1174
  }
1175
+ }
1176
+
1177
+ return exp
1178
+ })
1179
+ }
1180
+
1181
+ function parseMustache (raw = '', expHandler = exp => exp, strHandler = str => str) {
1182
+ let replaced = false
1183
+ if (tagRE.test(raw)) {
1184
+ const ret = []
1185
+ let lastLastIndex = 0
1186
+ let match
1187
+ while (match = tagREG.exec(raw)) {
1188
+ const pre = raw.substring(lastLastIndex, match.index)
1189
+ if (pre) {
1190
+ const pre2 = strHandler(pre)
1191
+ if (pre2 !== pre) replaced = true
1192
+ if (pre2) ret.push(stringify(pre2))
1193
+ }
1194
+
1195
+ const exp = match[1].trim()
1196
+ if (exp) {
1197
+ const exp2 = expHandler(exp)
1198
+ if (exp2 !== exp) replaced = true
1199
+ if (exp2) ret.push(`(${exp2})`)
1200
+ }
1187
1201
 
1188
- ret.push(`(${exp.trim()})`)
1189
1202
  lastLastIndex = tagREG.lastIndex
1190
1203
  }
1204
+
1191
1205
  const post = raw.substring(lastLastIndex)
1192
1206
  if (post) {
1193
- ret.push(stringify(post))
1207
+ const post2 = strHandler(post)
1208
+ if (post2 !== post) replaced = true
1209
+ if (post2) ret.push(stringify(post2))
1194
1210
  }
1211
+
1195
1212
  let result
1196
1213
  if (ret.length === 1) {
1197
1214
  result = ret[0]
1198
1215
  } else {
1199
1216
  result = `(${ret.join('+')})`
1200
1217
  }
1218
+
1201
1219
  return {
1202
1220
  result,
1203
1221
  hasBinding: true,
@@ -1205,10 +1223,14 @@ function parseMustache (raw = '') {
1205
1223
  replaced
1206
1224
  }
1207
1225
  }
1226
+
1227
+ const raw2 = strHandler(raw)
1228
+ if (raw2 !== raw) replaced = true
1229
+
1208
1230
  return {
1209
- result: stringify(raw),
1231
+ result: stringify(raw2),
1210
1232
  hasBinding: false,
1211
- val: raw,
1233
+ val: raw2,
1212
1234
  replaced
1213
1235
  }
1214
1236
  }
@@ -1226,14 +1248,14 @@ function processIf (el) {
1226
1248
  let val = getAndRemoveAttr(el, config[mode].directive.if).val
1227
1249
  if (val) {
1228
1250
  if (mode === 'swan') val = wrapMustache(val)
1229
- const parsed = parseMustache(val)
1251
+ const parsed = parseMustacheWithContext(val)
1230
1252
  el.if = {
1231
1253
  raw: parsed.val,
1232
1254
  exp: parsed.result
1233
1255
  }
1234
1256
  } else if (val = getAndRemoveAttr(el, config[mode].directive.elseif).val) {
1235
1257
  if (mode === 'swan') val = wrapMustache(val)
1236
- const parsed = parseMustache(val)
1258
+ const parsed = parseMustacheWithContext(val)
1237
1259
  el.elseif = {
1238
1260
  raw: parsed.val,
1239
1261
  exp: parsed.result
@@ -1275,7 +1297,7 @@ function processFor (el) {
1275
1297
  }
1276
1298
  } else {
1277
1299
  if (mode === 'swan') val = wrapMustache(val)
1278
- const parsed = parseMustache(val)
1300
+ const parsed = parseMustacheWithContext(val)
1279
1301
  el.for = {
1280
1302
  raw: parsed.val,
1281
1303
  exp: parsed.result
@@ -1387,14 +1409,14 @@ function processAttrs (el, options) {
1387
1409
  const isTemplateData = el.tag === 'template' && attr.name === 'data'
1388
1410
  const needWrap = isTemplateData && mode !== 'swan'
1389
1411
  const value = needWrap ? `{${attr.value}}` : attr.value
1390
- const parsed = parseMustache(value)
1412
+ const parsed = parseMustacheWithContext(value)
1391
1413
  if (parsed.hasBinding) {
1392
1414
  // 该属性判断用于提供给运行时对于计算属性作为props传递时提出警告
1393
1415
  const isProps = isComponentNode(el, options) && !(attr.name === 'class' || attr.name === 'style')
1394
1416
  addExp(el, parsed.result, isProps)
1395
- }
1396
- if (parsed.replaced) {
1397
- modifyAttr(el, attr.name, needWrap ? parsed.val.slice(1, -1) : parsed.val)
1417
+ if (parsed.replaced) {
1418
+ modifyAttr(el, attr.name, needWrap ? parsed.val.slice(1, -1) : parsed.val)
1419
+ }
1398
1420
  }
1399
1421
  })
1400
1422
  }
@@ -1526,7 +1548,7 @@ function processText (el) {
1526
1548
  if (el.type !== 3 || el.isComment) {
1527
1549
  return
1528
1550
  }
1529
- const parsed = parseMustache(el.text)
1551
+ const parsed = parseMustacheWithContext(el.text)
1530
1552
  if (parsed.hasBinding) {
1531
1553
  addExp(el, parsed.result)
1532
1554
  }
@@ -1571,8 +1593,8 @@ function processClass (el, meta) {
1571
1593
  let staticClass = getAndRemoveAttr(el, type).val || ''
1572
1594
  staticClass = staticClass.replace(/\s+/g, ' ')
1573
1595
  if (dynamicClass) {
1574
- const staticClassExp = parseMustache(staticClass).result
1575
- const dynamicClassExp = transDynamicClassExpr(parseMustache(dynamicClass).result, {
1596
+ const staticClassExp = parseMustacheWithContext(staticClass).result
1597
+ const dynamicClassExp = transDynamicClassExpr(parseMustacheWithContext(dynamicClass).result, {
1576
1598
  error: error$1
1577
1599
  })
1578
1600
  addAttrs(el, [{
@@ -1607,8 +1629,8 @@ function processStyle (el, meta) {
1607
1629
  let staticStyle = getAndRemoveAttr(el, type).val || ''
1608
1630
  staticStyle = staticStyle.replace(/\s+/g, ' ')
1609
1631
  if (dynamicStyle) {
1610
- const staticStyleExp = parseMustache(staticStyle).result
1611
- const dynamicStyleExp = parseMustache(dynamicStyle).result
1632
+ const staticStyleExp = parseMustacheWithContext(staticStyle).result
1633
+ const dynamicStyleExp = parseMustacheWithContext(dynamicStyle).result
1612
1634
  addAttrs(el, [{
1613
1635
  name: targetType,
1614
1636
  value: `{{${stringifyModuleName}.stringifyStyle(${staticStyleExp}, ${dynamicStyleExp})}}`
@@ -1866,7 +1888,7 @@ function processShow (el, options, root) {
1866
1888
  if (options.hasVirtualHost) {
1867
1889
  if (options.isComponent && el.parent === root && isRealNode(el)) {
1868
1890
  if (show !== undefined) {
1869
- show = `{{${parseMustache(show).result}&&mpxShow}}`
1891
+ show = `{{${parseMustacheWithContext(show).result}&&mpxShow}}`
1870
1892
  } else {
1871
1893
  show = '{{mpxShow}}'
1872
1894
  }
@@ -1888,7 +1910,7 @@ function processShow (el, options, root) {
1888
1910
 
1889
1911
  function processShowStyle () {
1890
1912
  if (show !== undefined) {
1891
- const showExp = parseMustache(show).result
1913
+ const showExp = parseMustacheWithContext(show).result
1892
1914
  let oldStyle = getAndRemoveAttr(el, 'style').val
1893
1915
  oldStyle = oldStyle ? oldStyle + ';' : ''
1894
1916
  addAttrs(el, [{
@@ -2372,6 +2394,7 @@ module.exports = {
2372
2394
  makeAttrsMap,
2373
2395
  stringifyAttr,
2374
2396
  parseMustache,
2397
+ parseMustacheWithContext,
2375
2398
  stringifyWithResolveComputed,
2376
2399
  addAttrs
2377
2400
  }
@@ -0,0 +1,56 @@
1
+ const addQuery = require('../utils/add-query')
2
+ const normalize = require('../utils/normalize')
3
+ const optionProcessorPath = normalize.lib('runtime/optionProcessor')
4
+ const { buildComponentsMap, buildPagesMap, buildGlobalParams, shallowStringify, stringifyRequest, buildI18n } = require('./script-helper')
5
+
6
+ module.exports = function (script, {
7
+ loaderContext,
8
+ ctorType,
9
+ srcMode,
10
+ moduleId,
11
+ isProduction,
12
+ jsonConfig,
13
+ localComponentsMap,
14
+ tabBar,
15
+ tabBarMap,
16
+ tabBarStr,
17
+ localPagesMap,
18
+ resource
19
+ }, callback) {
20
+ const { i18n, webConfig } = loaderContext.getMpx()
21
+
22
+ const { pagesMap, firstPage, globalTabBar } = buildPagesMap({ localPagesMap, loaderContext, tabBar, tabBarMap, tabBarStr, jsonConfig })
23
+
24
+ const componentsMap = buildComponentsMap({ localComponentsMap, loaderContext })
25
+
26
+ const scriptSrcMode = script ? script.mode || srcMode : srcMode
27
+
28
+ let output = `\n import { processAppOption, getComponent } from ${stringifyRequest(loaderContext, optionProcessorPath)}
29
+ import '@mpxjs/webpack-plugin/lib/runtime/base.styl'
30
+ import Vue from 'vue'
31
+ import VueRouter from 'vue-router'
32
+ import Mpx from '@mpxjs/core'
33
+ import App from ${stringifyRequest(loaderContext, addQuery(resource, { isApp: true }))}
34
+ Vue.use(VueRouter)
35
+ \n`
36
+
37
+ if (i18n) {
38
+ output += buildI18n({ i18n, loaderContext })
39
+ }
40
+
41
+ output += buildGlobalParams({ moduleId, scriptSrcMode, loaderContext, isProduction, jsonConfig, webConfig, isMain: true, globalTabBar })
42
+ output += `export default processAppOption({
43
+ App,
44
+ tabBarMap: ${JSON.stringify(tabBarMap)},
45
+ firstPage: ${JSON.stringify(firstPage)},
46
+ pagesMap: ${shallowStringify(pagesMap)},
47
+ componentsMap: ${shallowStringify(componentsMap)},
48
+ Vue,
49
+ VueRouter,
50
+ webConfig: ${JSON.stringify(webConfig)}
51
+ })`
52
+
53
+ callback(null, {
54
+ output
55
+ })
56
+ }
@@ -1,33 +1,8 @@
1
1
  const genComponentTag = require('../utils/gen-component-tag')
2
2
  const loaderUtils = require('loader-utils')
3
- const addQuery = require('../utils/add-query')
4
3
  const normalize = require('../utils/normalize')
5
- const hasOwn = require('../utils/has-own')
6
- const createHelpers = require('../helpers')
7
4
  const optionProcessorPath = normalize.lib('runtime/optionProcessor')
8
- const tabBarContainerPath = normalize.lib('runtime/components/web/mpx-tab-bar-container.vue')
9
- const tabBarPath = normalize.lib('runtime/components/web/mpx-tab-bar.vue')
10
-
11
- function shallowStringify (obj) {
12
- const arr = []
13
- for (const key in obj) {
14
- if (hasOwn(obj, key)) {
15
- let value = obj[key]
16
- if (Array.isArray(value)) {
17
- value = `[${value.join(',')}]`
18
- }
19
- arr.push(`'${key}':${value}`)
20
- }
21
- }
22
- return `{${arr.join(',')}}`
23
- }
24
-
25
- function getAsyncChunkName (chunkName) {
26
- if (chunkName && typeof chunkName !== 'boolean') {
27
- return `/* webpackChunkName: "${chunkName}" */`
28
- }
29
- return ''
30
- }
5
+ const { buildComponentsMap, getRequireScript, buildGlobalParams, shallowStringify } = require('./script-helper')
31
6
 
32
7
  module.exports = function (script, {
33
8
  loaderContext,
@@ -38,50 +13,14 @@ module.exports = function (script, {
38
13
  componentGenerics,
39
14
  jsonConfig,
40
15
  outputPath,
41
- tabBarMap,
42
- tabBarStr,
43
16
  builtInComponentsMap,
44
17
  genericsInfo,
45
18
  wxsModuleMap,
46
- localComponentsMap,
47
- localPagesMap
19
+ localComponentsMap
48
20
  }, callback) {
49
- const {
50
- i18n,
51
- projectRoot,
52
- webConfig,
53
- appInfo
54
- } = loaderContext.getMpx()
55
- const { getRequire } = createHelpers(loaderContext)
56
- const tabBar = jsonConfig.tabBar
57
-
58
- const emitWarning = (msg) => {
59
- loaderContext.emitWarning(
60
- new Error('[script processor][' + loaderContext.resource + ']: ' + msg)
61
- )
62
- }
21
+ const { projectRoot, appInfo } = loaderContext.getMpx()
63
22
 
64
23
  const stringifyRequest = r => loaderUtils.stringifyRequest(loaderContext, r)
65
- const tabBarPagesMap = {}
66
- if (tabBar && tabBarMap) {
67
- // 挂载tabBar组件
68
- const tabBarRequest = stringifyRequest(addQuery(tabBar.custom ? './custom-tab-bar/index' : tabBarPath, { isComponent: true }))
69
- tabBarPagesMap['mpx-tab-bar'] = `getComponent(require(${tabBarRequest}))`
70
- // 挂载tabBar页面
71
- Object.keys(tabBarMap).forEach((pagePath) => {
72
- const pageCfg = localPagesMap[pagePath]
73
- if (pageCfg) {
74
- const pageRequest = stringifyRequest(pageCfg.resource)
75
- if (pageCfg.async) {
76
- tabBarPagesMap[pagePath] = `()=>import(${getAsyncChunkName(pageCfg.async)}${pageRequest}).then(res => getComponent(res, { __mpxPageRoute: ${JSON.stringify(pagePath)} }))`
77
- } else {
78
- tabBarPagesMap[pagePath] = `getComponent(require(${pageRequest}), { __mpxPageRoute: ${JSON.stringify(pagePath)} })`
79
- }
80
- } else {
81
- emitWarning(`TabBar page path ${pagePath} is not exist in local page map, please check!`)
82
- }
83
- })
84
- }
85
24
 
86
25
  let output = '/* script */\n'
87
26
 
@@ -101,59 +40,7 @@ module.exports = function (script, {
101
40
  return attrs
102
41
  },
103
42
  content (script) {
104
- let content = `\n import processOption, { getComponent, getWxsMixin } from ${stringifyRequest(optionProcessorPath)}\n`
105
- // add import
106
- if (ctorType === 'app') {
107
- content += ` import '@mpxjs/webpack-plugin/lib/runtime/base.styl'
108
- import Vue from 'vue'
109
- import VueRouter from 'vue-router'
110
- import Mpx from '@mpxjs/core'
111
- Vue.use(VueRouter)
112
- global.getApp = function(){}
113
- global.getCurrentPages = function(){
114
- const router = global.__mpxRouter
115
- if(!router) return []
116
- // @ts-ignore
117
- return (router.lastStack || router.stack).map(item => {
118
- let page
119
- const vnode = item.vnode
120
- if(vnode && vnode.componentInstance) {
121
- page = vnode.tag.endsWith('mpx-tab-bar-container') ? vnode.componentInstance.$refs.tabBarPage : vnode.componentInstance
122
- }
123
- return page || { route: item.path.slice(1) }
124
- })
125
- }
126
- global.__networkTimeout = ${JSON.stringify(jsonConfig.networkTimeout)}
127
- global.__mpxGenericsMap = {}
128
- global.__mpxOptionsMap = {}
129
- global.__style = ${JSON.stringify(jsonConfig.style || 'v1')}
130
- global.__mpxPageConfig = ${JSON.stringify(jsonConfig.window)}
131
- global.__mpxTransRpxFn = ${webConfig.transRpxFn}\n`
132
- if (i18n) {
133
- const i18nObj = Object.assign({}, i18n)
134
- content += ` import VueI18n from 'vue-i18n'
135
- import { createI18n } from 'vue-i18n-bridge'
136
-
137
- Vue.use(VueI18n , { bridge: true })\n`
138
- const requestObj = {}
139
- const i18nKeys = ['messages', 'dateTimeFormats', 'numberFormats']
140
- i18nKeys.forEach((key) => {
141
- if (i18nObj[`${key}Path`]) {
142
- requestObj[key] = stringifyRequest(i18nObj[`${key}Path`])
143
- delete i18nObj[`${key}Path`]
144
- }
145
- })
146
- content += ` const i18nCfg = ${JSON.stringify(i18nObj)}\n`
147
- Object.keys(requestObj).forEach((key) => {
148
- content += ` i18nCfg.${key} = require(${requestObj[key]})\n`
149
- })
150
- content += ' i18nCfg.legacy = false\n'
151
- content += ` const i18n = createI18n(i18nCfg, VueI18n)
152
- Vue.use(i18n)
153
- Mpx.i18n = i18n
154
- \n`
155
- }
156
- }
43
+ let content = `\n import processComponentOption, { getComponent, getWxsMixin } from ${stringifyRequest(optionProcessorPath)}\n`
157
44
  let hasApp = true
158
45
  if (!appInfo.name) {
159
46
  hasApp = false
@@ -167,65 +54,10 @@ module.exports = function (script, {
167
54
  content += ` wxsModules.${module} = ${expression}\n`
168
55
  })
169
56
  }
170
- let firstPage = ''
171
- const pagesMap = {}
172
- const componentsMap = {}
173
- Object.keys(localPagesMap).forEach((pagePath) => {
174
- const pageCfg = localPagesMap[pagePath]
175
- const pageRequest = stringifyRequest(pageCfg.resource)
176
- if (tabBarMap && tabBarMap[pagePath]) {
177
- pagesMap[pagePath] = `getComponent(require(${stringifyRequest(tabBarContainerPath)}), { __mpxBuiltIn: true })`
178
- } else {
179
- if (pageCfg.async) {
180
- pagesMap[pagePath] = `()=>import(${getAsyncChunkName(pageCfg.async)} ${pageRequest}).then(res => getComponent(res, { __mpxPageRoute: ${JSON.stringify(pagePath)} }))`
181
- } else {
182
- // 为了保持小程序中app->page->component的js执行顺序,所有的page和component都改为require引入
183
- pagesMap[pagePath] = `getComponent(require(${pageRequest}), { __mpxPageRoute: ${JSON.stringify(pagePath)} })`
184
- }
185
- }
186
- if (pagePath === jsonConfig.entryPagePath) {
187
- firstPage = pagePath
188
- }
189
- if (!firstPage && pageCfg.isFirst) {
190
- firstPage = pagePath
191
- }
192
- })
193
-
194
- Object.keys(localComponentsMap).forEach((componentName) => {
195
- const componentCfg = localComponentsMap[componentName]
196
- const componentRequest = stringifyRequest(componentCfg.resource)
197
- if (componentCfg.async) {
198
- componentsMap[componentName] = `()=>import(${getAsyncChunkName(componentCfg.async)}${componentRequest}).then(res => getComponent(res))`
199
- } else {
200
- componentsMap[componentName] = `getComponent(require(${componentRequest}))`
201
- }
202
- })
203
-
204
- Object.keys(builtInComponentsMap).forEach((componentName) => {
205
- const componentCfg = builtInComponentsMap[componentName]
206
- const componentRequest = stringifyRequest(componentCfg.resource)
207
- componentsMap[componentName] = `getComponent(require(${componentRequest}), { __mpxBuiltIn: true })`
208
- })
209
-
210
- content += ` global.currentModuleId = ${JSON.stringify(moduleId)}\n`
211
- content += ` global.currentSrcMode = ${JSON.stringify(scriptSrcMode)}\n`
212
- content += ` global.currentInject = ${JSON.stringify({ moduleId })}\n`
213
- if (!isProduction) {
214
- content += ` global.currentResource = ${JSON.stringify(loaderContext.resourcePath)}\n`
215
- }
216
-
217
- content += ' /** script content **/\n'
218
57
 
219
- // 传递ctorType以补全js内容
220
- const extraOptions = {
221
- ctorType,
222
- lang: script.lang || 'js'
223
- }
224
- // todo 仅靠vueContentCache保障模块唯一性还是不够严谨,后续需要考虑去除原始query后构建request
225
- content += ` ${getRequire('script', script, extraOptions)}\n`
58
+ // 获取组件集合
59
+ const componentsMap = buildComponentsMap({ localComponentsMap, builtInComponentsMap, loaderContext })
226
60
 
227
- // createApp/Page/Component执行完成后立刻获取当前的option并暂存
228
- content += ` const currentOption = global.__mpxOptionsMap[${JSON.stringify(moduleId)}]\n`
229
61
  // 获取pageConfig
230
62
  const pageConfig = {}
231
63
  if (ctorType === 'page') {
@@ -240,36 +72,21 @@ module.exports = function (script, {
240
72
  pageConfig[key] = jsonConfig[key]
241
73
  })
242
74
  }
243
- // 为了执行顺序正确,tabBarPagesMap在app逻辑执行完成后注入,保障小程序中app->page->component的js执行顺序
244
- if (tabBarStr && tabBarPagesMap) {
245
- content += ` global.__tabBar = ${tabBarStr}
246
- Vue.observable(global.__tabBar)
247
- // @ts-ignore
248
- global.__tabBarPagesMap = ${shallowStringify(tabBarPagesMap)}\n`
249
- }
250
- // 配置平台转换通过createFactory在core中convertor中定义和进行
251
- // 通过processOption进行组件注册和路由注入
252
- content += ` export default processOption(
253
- currentOption,
254
- ${JSON.stringify(ctorType)},
255
- ${JSON.stringify(firstPage)},
256
- ${JSON.stringify(outputPath)},
257
- ${JSON.stringify(pageConfig)},
258
- // @ts-ignore
259
- ${shallowStringify(pagesMap)},
75
+
76
+ content += buildGlobalParams({ moduleId, scriptSrcMode, loaderContext, isProduction })
77
+ content += getRequireScript({ ctorType, script, loaderContext })
78
+ content += ` export default processComponentOption({
79
+ option: global.__mpxOptionsMap[${JSON.stringify(moduleId)}],
80
+ ctorType: ${JSON.stringify(ctorType)},
81
+ outputPath: ${JSON.stringify(outputPath)},
82
+ pageConfig: ${JSON.stringify(pageConfig)},
260
83
  // @ts-ignore
261
- ${shallowStringify(componentsMap)},
262
- ${JSON.stringify(tabBarMap)},
263
- ${JSON.stringify(componentGenerics)},
264
- ${JSON.stringify(genericsInfo)},
265
- getWxsMixin(wxsModules),
266
- ${hasApp}`
267
- if (ctorType === 'app') {
268
- content += `,
269
- Vue,
270
- VueRouter`
271
- }
272
- content += '\n )\n'
84
+ componentsMap: ${shallowStringify(componentsMap)},
85
+ componentGenerics: ${JSON.stringify(componentGenerics)},
86
+ genericsInfo: ${JSON.stringify(genericsInfo)},
87
+ mixin: getWxsMixin(wxsModules),
88
+ hasApp: ${hasApp}`
89
+ content += '\n })\n'
273
90
  return content
274
91
  }
275
92
  })
@@ -23,6 +23,7 @@ module.exports = function (template, {
23
23
  decodeHTMLText,
24
24
  externalClasses,
25
25
  checkUsingComponents,
26
+ webConfig,
26
27
  autoVirtualHostRules
27
28
  } = mpx
28
29
  const { resourcePath } = parseRequest(loaderContext.resource)
@@ -32,9 +33,11 @@ module.exports = function (template, {
32
33
  let output = '/* template */\n'
33
34
 
34
35
  if (ctorType === 'app') {
36
+ const { el } = webConfig
37
+ const idName = el?.match(/#(.*)/)?.[1] || 'app'
35
38
  template = {
36
39
  tag: 'template',
37
- content: '<div class="app"><mpx-keep-alive><router-view class="page"></router-view></mpx-keep-alive></div>'
40
+ content: `<div id="${idName}"><mpx-keep-alive><router-view></router-view></mpx-keep-alive></div>`
38
41
  }
39
42
  builtInComponentsMap['mpx-keep-alive'] = {
40
43
  resource: addQuery('@mpxjs/webpack-plugin/lib/runtime/components/web/mpx-keep-alive.vue', { isComponent: true })