@mpxjs/webpack-plugin 2.10.7-beta.9 → 2.10.8

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.
Files changed (42) hide show
  1. package/LICENSE +433 -0
  2. package/lib/dependencies/RequireExternalDependency.js +61 -0
  3. package/lib/file-loader.js +3 -2
  4. package/lib/index.js +60 -15
  5. package/lib/json-compiler/index.js +1 -0
  6. package/lib/parser.js +1 -1
  7. package/lib/platform/json/wx/index.js +43 -25
  8. package/lib/platform/template/wx/component-config/fix-component-name.js +2 -2
  9. package/lib/platform/template/wx/component-config/movable-view.js +10 -1
  10. package/lib/platform/template/wx/index.js +2 -1
  11. package/lib/react/LoadAsyncChunkModule.js +74 -0
  12. package/lib/react/index.js +3 -1
  13. package/lib/react/processJSON.js +74 -13
  14. package/lib/react/processScript.js +6 -6
  15. package/lib/react/script-helper.js +100 -41
  16. package/lib/runtime/components/react/context.ts +2 -12
  17. package/lib/runtime/components/react/dist/context.js +1 -1
  18. package/lib/runtime/components/react/dist/getInnerListeners.js +1 -1
  19. package/lib/runtime/components/react/dist/mpx-async-suspense.jsx +135 -0
  20. package/lib/runtime/components/react/dist/mpx-movable-area.jsx +9 -63
  21. package/lib/runtime/components/react/dist/mpx-movable-view.jsx +58 -301
  22. package/lib/runtime/components/react/dist/mpx-swiper.jsx +27 -53
  23. package/lib/runtime/components/react/dist/mpx-web-view.jsx +14 -28
  24. package/lib/runtime/components/react/dist/useAnimationHooks.js +2 -87
  25. package/lib/runtime/components/react/getInnerListeners.ts +1 -1
  26. package/lib/runtime/components/react/mpx-async-suspense.tsx +180 -0
  27. package/lib/runtime/components/react/mpx-movable-area.tsx +11 -98
  28. package/lib/runtime/components/react/mpx-movable-view.tsx +60 -350
  29. package/lib/runtime/components/react/mpx-swiper.tsx +25 -53
  30. package/lib/runtime/components/react/mpx-web-view.tsx +13 -33
  31. package/lib/runtime/components/react/types/global.d.ts +15 -0
  32. package/lib/runtime/components/react/useAnimationHooks.ts +2 -85
  33. package/lib/runtime/optionProcessorReact.d.ts +18 -0
  34. package/lib/runtime/optionProcessorReact.js +30 -0
  35. package/lib/script-setup-compiler/index.js +27 -5
  36. package/lib/template-compiler/compiler.js +4 -3
  37. package/lib/utils/dom-tag-config.js +17 -3
  38. package/lib/utils/trans-async-sub-rules.js +19 -0
  39. package/lib/web/script-helper.js +1 -1
  40. package/package.json +4 -4
  41. package/lib/runtime/components/react/AsyncContainer.tsx +0 -189
  42. package/lib/runtime/components/react/dist/AsyncContainer.jsx +0 -141
@@ -623,6 +623,7 @@ module.exports = function (content) {
623
623
  }
624
624
  if (err) return callback(err)
625
625
  genericComponents[name] = entry
626
+ callback()
626
627
  })
627
628
  }, callback)
628
629
  }, callback)
package/lib/parser.js CHANGED
@@ -14,7 +14,7 @@ module.exports = (content, { filePath, needMap, mode, env }) => {
14
14
  output = compiler.parseComponent(content, {
15
15
  mode,
16
16
  filePath,
17
- // pad: 'line', // stylus编译遇到大量空行时会出现栈溢出,故注释掉
17
+ pad: 'line',
18
18
  env
19
19
  })
20
20
  if (needMap) {
@@ -3,7 +3,7 @@ const normalizeTest = require('../normalize-test')
3
3
  const changeKey = require('../change-key')
4
4
  const normalize = require('../../../utils/normalize')
5
5
  const { capitalToHyphen } = require('../../../utils/string')
6
- const { isOriginTag, isBuildInTag } = require('../../../utils/dom-tag-config')
6
+ const { isOriginTag, isBuildInWebTag, isBuildInReactTag } = require('../../../utils/dom-tag-config')
7
7
 
8
8
  const mpxViewPath = normalize.lib('runtime/components/ali/mpx-view.mpx')
9
9
  const mpxTextPath = normalize.lib('runtime/components/ali/mpx-text.mpx')
@@ -128,19 +128,41 @@ module.exports = function getSpec ({ warn, error }) {
128
128
  /**
129
129
  * 将小程序代码中使用的与原生 HTML tag 或 内建组件 同名的组件进行转化,以解决与原生tag命名冲突问题。
130
130
  */
131
- function fixComponentName (type) {
132
- return function (input) {
133
- const usingComponents = input[type]
134
- if (usingComponents) {
135
- Object.keys(usingComponents).forEach(tag => {
136
- if (isOriginTag(tag) || isBuildInTag(tag)) {
137
- usingComponents[`mpx-com-${tag}`] = usingComponents[tag]
138
- delete usingComponents[tag]
131
+ function fixComponentName (input, { mode }) {
132
+ const isNeedFixTag = (tag) => {
133
+ switch (mode) {
134
+ case 'web': return isOriginTag(tag) || isBuildInWebTag(tag)
135
+ case 'ios':
136
+ case 'android':
137
+ case 'harmony': return isOriginTag(tag) || isBuildInReactTag(tag)
138
+ }
139
+ }
140
+
141
+ const usingComponents = input.usingComponents
142
+ const componentPlaceholder = input.componentPlaceholder
143
+ if (usingComponents) {
144
+ const transfromKeys = []
145
+ Object.keys(usingComponents).forEach(tag => {
146
+ if (isNeedFixTag(tag)) {
147
+ usingComponents[`mpx-com-${tag}`] = usingComponents[tag]
148
+ delete usingComponents[tag]
149
+ transfromKeys.push(tag)
150
+ }
151
+ })
152
+
153
+ if (transfromKeys.length && componentPlaceholder) {
154
+ Object.keys(componentPlaceholder).forEach(key => {
155
+ if (transfromKeys.includes(componentPlaceholder[key])) {
156
+ componentPlaceholder[key] = `mpx-com-${componentPlaceholder[key]}`
157
+ }
158
+ if (transfromKeys.includes(key)) {
159
+ componentPlaceholder[`mpx-com-${key}`] = componentPlaceholder[key]
160
+ delete componentPlaceholder[key]
139
161
  }
140
162
  })
141
163
  }
142
- return input
143
164
  }
165
+ return input
144
166
  }
145
167
 
146
168
  const componentRules = [
@@ -154,13 +176,6 @@ module.exports = function getSpec ({ warn, error }) {
154
176
  swan: deletePath(),
155
177
  jd: deletePath()
156
178
  },
157
- {
158
- test: 'usingComponents',
159
- web: fixComponentName('usingComponents'),
160
- ios: fixComponentName('usingComponents'),
161
- android: fixComponentName('usingComponents'),
162
- harmony: fixComponentName('usingComponents')
163
- },
164
179
  {
165
180
  test: 'usingComponents',
166
181
  ali: componentNameCapitalToHyphen('usingComponents'),
@@ -170,7 +185,11 @@ module.exports = function getSpec ({ warn, error }) {
170
185
  swan: addGlobalComponents,
171
186
  qq: addGlobalComponents,
172
187
  tt: addGlobalComponents,
173
- jd: addGlobalComponents
188
+ jd: addGlobalComponents,
189
+ web: fixComponentName,
190
+ ios: fixComponentName,
191
+ android: fixComponentName,
192
+ harmony: fixComponentName
174
193
  }
175
194
  ]
176
195
 
@@ -371,13 +390,6 @@ module.exports = function getSpec ({ warn, error }) {
371
390
  tt: deletePath(),
372
391
  jd: deletePath(true)
373
392
  },
374
- {
375
- test: 'usingComponents',
376
- web: fixComponentName('usingComponents'),
377
- ios: fixComponentName('usingComponents'),
378
- android: fixComponentName('usingComponents'),
379
- harmony: fixComponentName('usingComponents')
380
- },
381
393
  {
382
394
  test: 'usingComponents',
383
395
  ali: componentNameCapitalToHyphen('usingComponents'),
@@ -442,6 +454,12 @@ module.exports = function getSpec ({ warn, error }) {
442
454
  swan: getWindowRule(),
443
455
  tt: getWindowRule(),
444
456
  jd: getWindowRule()
457
+ },
458
+ {
459
+ web: fixComponentName,
460
+ ios: fixComponentName,
461
+ android: fixComponentName,
462
+ harmony: fixComponentName
445
463
  }
446
464
  ]
447
465
  }
@@ -1,4 +1,4 @@
1
- const { isOriginTag, isBuildInTag } = require('../../../../utils/dom-tag-config')
1
+ const { isOriginTag, isBuildInWebTag } = require('../../../../utils/dom-tag-config')
2
2
 
3
3
  module.exports = function () {
4
4
  const handleComponentTag = (el, data) => {
@@ -16,7 +16,7 @@ module.exports = function () {
16
16
  waterfall: true,
17
17
  skipNormalize: true,
18
18
  supportedModes: ['web', 'ios', 'android', 'harmony'],
19
- test: (input) => isOriginTag(input) || isBuildInTag(input),
19
+ test: (input) => isOriginTag(input) || isBuildInWebTag(input),
20
20
  web: handleComponentTag,
21
21
  ios: handleComponentTag,
22
22
  android: handleComponentTag,
@@ -2,6 +2,9 @@ const TAG_NAME = 'movable-view'
2
2
 
3
3
  module.exports = function ({ print }) {
4
4
  const aliEventLog = print({ platform: 'ali', tag: TAG_NAME, isError: false, type: 'event' })
5
+ const androidEventLog = print({ platform: 'android', tag: TAG_NAME, isError: false, type: 'event' })
6
+ const harmonyEventLog = print({ platform: 'harmony', tag: TAG_NAME, isError: false, type: 'event' })
7
+ const iosEventLog = print({ platform: 'ios', tag: TAG_NAME, isError: false, type: 'event' })
5
8
  const qaPropLog = print({ platform: 'qa', tag: TAG_NAME, isError: false })
6
9
  const androidPropLog = print({ platform: 'android', tag: TAG_NAME, isError: false })
7
10
  const harmonyPropLog = print({ platform: 'harmony', tag: TAG_NAME, isError: false })
@@ -33,7 +36,7 @@ module.exports = function ({ print }) {
33
36
  harmony: harmonyPropLog
34
37
  },
35
38
  {
36
- test: /^(damping|friction)$/,
39
+ test: /^(damping|friction|scale|scale-min|scale-max|scale-value)$/,
37
40
  ios: iosPropLog,
38
41
  android: androidPropLog,
39
42
  harmony: harmonyPropLog
@@ -43,6 +46,12 @@ module.exports = function ({ print }) {
43
46
  {
44
47
  test: /^(htouchmove|vtouchmove)$/,
45
48
  ali: aliEventLog
49
+ },
50
+ {
51
+ test: /^(bindscale)$/,
52
+ ios: iosEventLog,
53
+ android: androidEventLog,
54
+ harmony: harmonyEventLog
46
55
  }
47
56
  ]
48
57
  }
@@ -34,7 +34,8 @@ module.exports = function getSpec ({ warn, error }) {
34
34
  touchstart: 'touchstart',
35
35
  touchmove: 'touchmove',
36
36
  touchend: 'touchend',
37
- touchcancel: 'touchcancel'
37
+ touchcancel: 'touchcancel',
38
+ transitionend: 'transitionend'
38
39
  }
39
40
  if (eventMap[eventName]) {
40
41
  return eventMap[eventName]
@@ -0,0 +1,74 @@
1
+ const RuntimeGlobals = require('webpack/lib/RuntimeGlobals')
2
+ const Template = require('webpack/lib/Template')
3
+ const HelperRuntimeModule = require('webpack/lib/runtime/HelperRuntimeModule')
4
+
5
+ class LoadAsyncChunkRuntimeModule extends HelperRuntimeModule {
6
+ constructor (timeout) {
7
+ super('load async chunk')
8
+ this.timeout = timeout || 5000
9
+ }
10
+
11
+ generate () {
12
+ const { compilation } = this
13
+ const { runtimeTemplate } = compilation
14
+ const loadScriptFn = RuntimeGlobals.loadScript
15
+ return Template.asString([
16
+ 'var inProgress = {}',
17
+ `${loadScriptFn} = ${runtimeTemplate.basicFunction(
18
+ 'url, done, key, chunkId',
19
+ [
20
+ `var packageName = ${RuntimeGlobals.getChunkScriptFilename}(chunkId) || ''`,
21
+ 'packageName = packageName.split(\'/\').slice(0, -1).join(\'/\')',
22
+ 'var config = {',
23
+ Template.indent([
24
+ 'url: url,',
25
+ 'package: packageName'
26
+ ]),
27
+ '}',
28
+ 'if(inProgress[url]) {',
29
+ Template.indent([
30
+ 'inProgress[url].push(done)',
31
+ 'return'
32
+ ]),
33
+ '}',
34
+ 'inProgress[url] = [done]',
35
+ 'var callback = function (type, result) {',
36
+ Template.indent([
37
+ 'var event = {',
38
+ Template.indent([
39
+ 'type: type || \'fail\',',
40
+ 'target: {',
41
+ Template.indent(['src: url']),
42
+ '}'
43
+ ]),
44
+ '}'
45
+ ]),
46
+ Template.indent([
47
+ 'var doneFns = inProgress[url]',
48
+ 'clearTimeout(timeout)',
49
+ 'delete inProgress[url]',
50
+ `doneFns && doneFns.forEach(${runtimeTemplate.returningFunction(
51
+ 'fn(event)',
52
+ 'fn'
53
+ )})`
54
+ ]),
55
+ '}',
56
+ `var timeout = setTimeout(callback.bind(null, 'timeout'), ${this.timeout})`,
57
+ 'var loadChunkAsyncFn = global.__mpx.config.rnConfig && global.__mpx.config.rnConfig.loadChunkAsync',
58
+ 'try {',
59
+ Template.indent([
60
+ 'loadChunkAsyncFn(config).then(callback).catch(callback)'
61
+ ]),
62
+ '} catch (e) {',
63
+ Template.indent([
64
+ 'console.error(\'[Mpx runtime error]: please provide correct mpx.config.rnConfig.loadChunkAsync implemention!\', e)',
65
+ 'Promise.resolve().then(callback)'
66
+ ]),
67
+ '}'
68
+ ]
69
+ )}`
70
+ ])
71
+ }
72
+ }
73
+
74
+ module.exports = LoadAsyncChunkRuntimeModule
@@ -35,6 +35,7 @@ module.exports = function ({
35
35
  })
36
36
  }
37
37
  const mpx = loaderContext.getMpx()
38
+ const rnConfig = mpx.rnConfig
38
39
  // 通过RecordLoaderContentDependency和loaderContentCache确保子request不再重复生成loaderContent
39
40
  const cacheContent = mpx.loaderContentCache.get(loaderContext.resourcePath)
40
41
  if (cacheContent) return callback(null, cacheContent)
@@ -91,7 +92,8 @@ module.exports = function ({
91
92
  genericsInfo: templateRes.genericsInfo,
92
93
  wxsModuleMap: templateRes.wxsModuleMap,
93
94
  localComponentsMap: jsonRes.localComponentsMap,
94
- localPagesMap: jsonRes.localPagesMap
95
+ localPagesMap: jsonRes.localPagesMap,
96
+ rnConfig
95
97
  }, callback)
96
98
  }
97
99
  ], (err, scriptRes) => {
@@ -8,11 +8,15 @@ const addQuery = require('../utils/add-query')
8
8
  const parseComponent = require('../parser')
9
9
  const getJSONContent = require('../utils/get-json-content')
10
10
  const resolve = require('../utils/resolve')
11
+ const { transSubpackage } = require('../utils/trans-async-sub-rules')
11
12
  const createJSONHelper = require('../json-compiler/helper')
12
13
  const getRulesRunner = require('../platform/index')
13
14
  const { RESOLVE_IGNORED_ERR } = require('../utils/const')
15
+ const normalize = require('../utils/normalize')
14
16
  const RecordResourceMapDependency = require('../dependencies/RecordResourceMapDependency')
15
17
  const RecordPageConfigsMapDependency = require('../dependencies/RecordPageConfigsMapDependency')
18
+ const mpxViewPath = normalize.lib('runtime/components/react/dist/mpx-view.jsx')
19
+ const mpxTextPath = normalize.lib('runtime/components/react/dist/mpx-text.jsx')
16
20
 
17
21
  module.exports = function (jsonContent, {
18
22
  loaderContext,
@@ -133,6 +137,45 @@ module.exports = function (jsonContent, {
133
137
  isShow: true
134
138
  }
135
139
 
140
+ const fillInComponentPlaceholder = (name, placeholder, placeholderEntry) => {
141
+ const componentPlaceholder = jsonObj.componentPlaceholder || {}
142
+ if (componentPlaceholder[name]) return
143
+ componentPlaceholder[name] = placeholder
144
+ jsonObj.componentPlaceholder = componentPlaceholder
145
+ if (placeholderEntry && !jsonObj.usingComponents[placeholder]) jsonObj.usingComponents[placeholder] = placeholderEntry
146
+ }
147
+
148
+ const fillInComponentsMap = (name, entry, tarRoot) => {
149
+ const { resource, outputPath } = entry
150
+ const { resourcePath } = parseRequest(resource)
151
+ tarRoot = transSubpackage(mpx.transSubpackageRules, tarRoot)
152
+ componentsMap[resourcePath] = outputPath
153
+ loaderContext._module && loaderContext._module.addPresentationalDependency(new RecordResourceMapDependency(resourcePath, 'component', outputPath))
154
+ localComponentsMap[name] = {
155
+ resource: addQuery(resource, {
156
+ isComponent: true,
157
+ outputPath
158
+ }),
159
+ async: tarRoot
160
+ }
161
+ }
162
+
163
+ const normalizePlaceholder = (placeholder) => {
164
+ if (typeof placeholder === 'string') {
165
+ const placeholderMap = mode === 'ali'
166
+ ? {
167
+ view: { name: 'mpx-view', resource: mpxViewPath },
168
+ text: { name: 'mpx-text', resource: mpxTextPath }
169
+ }
170
+ : {}
171
+ placeholder = placeholderMap[placeholder] || { name: placeholder }
172
+ }
173
+ if (!placeholder.name) {
174
+ emitError('The asyncSubpackageRules configuration format of @mpxjs/webpack-plugin a is incorrect')
175
+ }
176
+ return placeholder
177
+ }
178
+
136
179
  const processTabBar = (tabBar, callback) => {
137
180
  if (tabBar) {
138
181
  tabBar = Object.assign({}, defaultTabbar, tabBar)
@@ -247,7 +290,7 @@ module.exports = function (jsonContent, {
247
290
  if (err) return callback(err === RESOLVE_IGNORED_ERR ? null : err)
248
291
  if (pageKeySet.has(key)) return callback()
249
292
  pageKeySet.add(key)
250
- const { resourcePath, queryObj } = parseRequest(resource)
293
+ const { resourcePath } = parseRequest(resource)
251
294
  if (localPagesMap[outputPath]) {
252
295
  const { resourcePath: oldResourcePath } = parseRequest(localPagesMap[outputPath].resource)
253
296
  if (oldResourcePath !== resourcePath) {
@@ -259,9 +302,11 @@ module.exports = function (jsonContent, {
259
302
 
260
303
  pagesMap[resourcePath] = outputPath
261
304
  loaderContext._module && loaderContext._module.addPresentationalDependency(new RecordResourceMapDependency(resourcePath, 'page', outputPath))
305
+ // 通过asyncSubPackagesNameRules对tarRoot进行修改,仅修改tarRoot,不修改outputPath页面路径
306
+ tarRoot = transSubpackage(mpx.transSubpackageRules, tarRoot)
262
307
  localPagesMap[outputPath] = {
263
308
  resource: addQuery(resource, { isPage: true }),
264
- async: queryObj.async || tarRoot,
309
+ async: tarRoot,
265
310
  isFirst
266
311
  }
267
312
  callback()
@@ -301,19 +346,35 @@ module.exports = function (jsonContent, {
301
346
  const processComponents = (components, context, callback) => {
302
347
  if (components) {
303
348
  async.eachOf(components, (component, name, callback) => {
304
- processComponent(component, context, {}, (err, { resource, outputPath } = {}, { tarRoot } = {}) => {
349
+ processComponent(component, context, {}, (err, entry = {}, { tarRoot, placeholder } = {}) => {
305
350
  if (err) return callback(err === RESOLVE_IGNORED_ERR ? null : err)
306
- const { resourcePath, queryObj } = parseRequest(resource)
307
- componentsMap[resourcePath] = outputPath
308
- loaderContext._module && loaderContext._module.addPresentationalDependency(new RecordResourceMapDependency(resourcePath, 'component', outputPath))
309
- localComponentsMap[name] = {
310
- resource: addQuery(resource, {
311
- isComponent: true,
312
- outputPath
313
- }),
314
- async: queryObj.async || tarRoot
351
+ fillInComponentsMap(name, entry, tarRoot)
352
+ const { relativePath } = entry
353
+
354
+ if (tarRoot) {
355
+ if (placeholder) {
356
+ placeholder = normalizePlaceholder(placeholder)
357
+ if (placeholder.resource) {
358
+ processComponent(placeholder.resource, projectRoot, { relativePath }, (err, entry) => {
359
+ if (err) return callback(err)
360
+ fillInComponentPlaceholder(name, placeholder.name, entry)
361
+ fillInComponentsMap(placeholder.name, entry, '')
362
+ callback()
363
+ })
364
+ } else {
365
+ fillInComponentPlaceholder(name, placeholder.name)
366
+ callback()
367
+ }
368
+ } else {
369
+ if (!jsonObj.componentPlaceholder || !jsonObj.componentPlaceholder[name]) {
370
+ const errMsg = `componentPlaceholder of "${name}" doesn't exist! \n\r`
371
+ emitError(errMsg)
372
+ }
373
+ callback()
374
+ }
375
+ } else {
376
+ callback()
315
377
  }
316
- callback()
317
378
  })
318
379
  }, callback)
319
380
  } else {
@@ -13,6 +13,7 @@ module.exports = function (script, {
13
13
  builtInComponentsMap,
14
14
  localComponentsMap,
15
15
  localPagesMap,
16
+ rnConfig,
16
17
  componentGenerics,
17
18
  genericsInfo
18
19
  }, callback) {
@@ -34,12 +35,13 @@ module.exports = function (script, {
34
35
  let output = '/* script */\n'
35
36
  if (ctorType === 'app') {
36
37
  output += `
37
- import { getComponent } from ${stringifyRequest(loaderContext, optionProcessorPath)}
38
+ import { getComponent, getAsyncSuspense } from ${stringifyRequest(loaderContext, optionProcessorPath)}
38
39
  \n`
39
40
  const { pagesMap, firstPage } = buildPagesMap({
40
41
  localPagesMap,
41
42
  loaderContext,
42
- jsonConfig
43
+ jsonConfig,
44
+ rnConfig
43
45
  })
44
46
  const componentsMap = buildComponentsMap({
45
47
  localComponentsMap,
@@ -50,9 +52,7 @@ import { getComponent } from ${stringifyRequest(loaderContext, optionProcessorPa
50
52
  output += getRequireScript({ ctorType, script, loaderContext })
51
53
  output += `export default global.__mpxOptionsMap[${JSON.stringify(moduleId)}]\n`
52
54
  } else {
53
- // RN环境暂不支持异步加载
54
- // output += 'import { lazy } from \'react\'\n'
55
- output += `import { getComponent } from ${stringifyRequest(loaderContext, optionProcessorPath)}\n`
55
+ output += `import { getComponent, getAsyncSuspense } from ${stringifyRequest(loaderContext, optionProcessorPath)}\n`
56
56
  // 获取组件集合
57
57
  const componentsMap = buildComponentsMap({
58
58
  localComponentsMap,
@@ -61,7 +61,7 @@ import { getComponent } from ${stringifyRequest(loaderContext, optionProcessorPa
61
61
  jsonConfig
62
62
  })
63
63
 
64
- output += buildGlobalParams({ moduleId, scriptSrcMode, loaderContext, isProduction, ctorType, jsonConfig, componentsMap, outputPath, genericsInfo, componentGenerics })
64
+ output += buildGlobalParams({ moduleId, scriptSrcMode, loaderContext, isProduction, ctorType, jsonConfig, componentsMap, outputPath, genericsInfo, componentGenerics, hasApp })
65
65
  output += getRequireScript({ ctorType, script, loaderContext })
66
66
  output += `export default global.__mpxOptionsMap[${JSON.stringify(moduleId)}]\n`
67
67
  }
@@ -3,30 +3,71 @@ const createHelpers = require('../helpers')
3
3
  const parseRequest = require('../utils/parse-request')
4
4
  const shallowStringify = require('../utils/shallow-stringify')
5
5
  const normalize = require('../utils/normalize')
6
+ const addQuery = require('../utils/add-query')
7
+ const { isBuildInReactTag } = require('../utils/dom-tag-config')
6
8
 
7
9
  function stringifyRequest (loaderContext, request) {
8
10
  return loaderUtils.stringifyRequest(loaderContext, request)
9
11
  }
10
12
 
11
- // function getAsyncChunkName (chunkName) {
12
- // if (chunkName && typeof chunkName !== 'boolean') {
13
- // return `/* webpackChunkName: "${chunkName}" */`
14
- // }
15
- // return ''
13
+ function getBuiltInComponentRequest (component) {
14
+ return JSON.stringify(addQuery(`@mpxjs/webpack-plugin/lib/runtime/components/react/dist/${component}`, { isComponent: true }))
15
+ }
16
+
17
+ function getAsyncChunkName (chunkName) {
18
+ if (chunkName && typeof chunkName !== 'boolean') {
19
+ return `/* webpackChunkName: "${chunkName}/index" */`
20
+ }
21
+ return ''
22
+ }
23
+
24
+ function getAsyncSuspense (type, moduleId, componentRequest, componentName, chunkName, fallback, loading) {
25
+ return `getAsyncSuspense({
26
+ type: ${JSON.stringify(type)},
27
+ moduleId: ${JSON.stringify(moduleId)},
28
+ chunkName: ${JSON.stringify(chunkName)},
29
+ loading: ${loading},
30
+ fallback: ${fallback},
31
+ getChildren () {
32
+ return import(${getAsyncChunkName(chunkName)}${componentRequest}).then(function (res) {
33
+ return getComponent(res, {displayName: ${JSON.stringify(componentName)}})
34
+ })
35
+ }
36
+ })`
37
+ }
38
+
39
+ function getComponent (componentRequest, componentName) {
40
+ return `getComponent(require(${componentRequest}), {displayName: ${JSON.stringify(componentName)}})`
41
+ }
42
+
43
+ function getBuiltInComponent (componentRequest) {
44
+ return `getComponent(require(${componentRequest}), {__mpxBuiltIn: true})`
45
+ }
46
+
47
+ // function getLazyPage (componentRequest) {
48
+ // return `getLazyPage(${getComponentGetter(getComponent(componentRequest, 'Page'))})`
16
49
  // }
17
50
 
18
- function buildPagesMap ({ localPagesMap, loaderContext, jsonConfig }) {
51
+ function getComponentGetter (component) {
52
+ return `function(){ return ${component} }`
53
+ }
54
+
55
+ function buildPagesMap ({ localPagesMap, loaderContext, jsonConfig, rnConfig }) {
19
56
  let firstPage = ''
20
57
  const pagesMap = {}
58
+ const mpx = loaderContext.getMpx()
21
59
  Object.keys(localPagesMap).forEach((pagePath) => {
22
60
  const pageCfg = localPagesMap[pagePath]
23
61
  const pageRequest = stringifyRequest(loaderContext, pageCfg.resource)
24
- // if (pageCfg.async) {
25
- // pagesMap[pagePath] = `lazy(function(){return import(${getAsyncChunkName(pageCfg.async)} ${pageRequest}).then(function(res){return getComponent(res, {__mpxPageRoute: ${JSON.stringify(pagePath)}, displayName: "Page"})})})`
26
- // } else {
27
- // 为了保持小程序中app->page->component的js执行顺序,所有的page和component都改为require引入
28
- pagesMap[pagePath] = `getComponent(require(${pageRequest}), {__mpxPageRoute: ${JSON.stringify(pagePath)}, displayName: "Page"})`
29
- // }
62
+ if (pageCfg.async) {
63
+ const moduleId = mpx.getModuleId(pageCfg.resource)
64
+ const fallback = rnConfig.asyncChunk && rnConfig.asyncChunk.fallback && getComponent(stringifyRequest(loaderContext, addQuery(rnConfig.asyncChunk.fallback, { isComponent: true })), 'PageFallback')
65
+ const loading = rnConfig.asyncChunk && rnConfig.asyncChunk.loading && getComponent(stringifyRequest(loaderContext, addQuery(rnConfig.asyncChunk.loading, { isComponent: true })), 'PageLoading')
66
+ pagesMap[pagePath] = getComponentGetter(getAsyncSuspense('page', moduleId, pageRequest, 'Page', pageCfg.async, fallback, loading))
67
+ } else {
68
+ // 为了保持小程序中app->page->component的js执行顺序,所有的page和component都改为require引入
69
+ pagesMap[pagePath] = getComponentGetter(getComponent(pageRequest, 'Page'))
70
+ }
30
71
  if (pagePath === jsonConfig.entryPagePath) {
31
72
  firstPage = pagePath
32
73
  }
@@ -42,30 +83,58 @@ function buildPagesMap ({ localPagesMap, loaderContext, jsonConfig }) {
42
83
 
43
84
  function buildComponentsMap ({ localComponentsMap, builtInComponentsMap, loaderContext, jsonConfig }) {
44
85
  const componentsMap = {}
86
+ const mpx = loaderContext.getMpx()
45
87
  if (localComponentsMap) {
46
88
  Object.keys(localComponentsMap).forEach((componentName) => {
47
89
  const componentCfg = localComponentsMap[componentName]
48
90
  const componentRequest = stringifyRequest(loaderContext, componentCfg.resource)
49
- // RN中暂不支持异步加载
50
- // if (componentCfg.async) {
51
- // componentsMap[componentName] = `lazy(function(){return import(${getAsyncChunkName(componentCfg.async)}${componentRequest}).then(function(res){return getComponent(res, {displayName: ${JSON.stringify(componentName)}})})})`
52
- // } else {
53
- componentsMap[componentName] = `getComponent(require(${componentRequest}), {displayName: ${JSON.stringify(componentName)}})`
54
- // }
91
+ if (componentCfg.async) {
92
+ const moduleId = mpx.getModuleId(componentCfg.resource)
93
+ const placeholder = jsonConfig.componentPlaceholder && jsonConfig.componentPlaceholder[componentName]
94
+ let fallback
95
+ if (placeholder) {
96
+ if (localComponentsMap[placeholder]) {
97
+ const placeholderCfg = localComponentsMap[placeholder]
98
+ const placeholderRequest = stringifyRequest(loaderContext, placeholderCfg.resource)
99
+ if (placeholderCfg.async) {
100
+ loaderContext.emitWarning(
101
+ new Error(`[json processor][${loaderContext.resource}]: componentPlaceholder ${placeholder} should not be a async component, please check!`)
102
+ )
103
+ }
104
+ fallback = getComponent(placeholderRequest, placeholder)
105
+ } else {
106
+ const tag = `mpx-${placeholder}`
107
+ if (isBuildInReactTag(tag)) {
108
+ fallback = getBuiltInComponent(getBuiltInComponentRequest(tag))
109
+ } else {
110
+ loaderContext.emitError(
111
+ new Error(`[json processor][${loaderContext.resource}]: componentPlaceholder ${placeholder} is not built-in component, please check!`)
112
+ )
113
+ }
114
+ }
115
+ } else {
116
+ loaderContext.emitError(
117
+ new Error(`[json processor][${loaderContext.resource}]: ${componentName} has no componentPlaceholder, please check!`)
118
+ )
119
+ }
120
+ componentsMap[componentName] = getComponentGetter(getAsyncSuspense('component', moduleId, componentRequest, componentName, componentCfg.async, fallback))
121
+ } else {
122
+ componentsMap[componentName] = getComponentGetter(getComponent(componentRequest, componentName))
123
+ }
55
124
  })
56
125
  }
57
126
  if (builtInComponentsMap) {
58
127
  Object.keys(builtInComponentsMap).forEach((componentName) => {
59
128
  const componentCfg = builtInComponentsMap[componentName]
60
129
  const componentRequest = stringifyRequest(loaderContext, componentCfg.resource)
61
- componentsMap[componentName] = `getComponent(require(${componentRequest}), {__mpxBuiltIn: true})`
130
+ componentsMap[componentName] = getComponentGetter(getBuiltInComponent(componentRequest))
62
131
  })
63
132
  }
64
133
  return componentsMap
65
134
  }
66
135
 
67
136
  function getRequireScript ({ script, ctorType, loaderContext }) {
68
- let content = ' /** script content **/\n'
137
+ let content = '/** script content **/\n'
69
138
  const { getRequire } = createHelpers(loaderContext)
70
139
  const { resourcePath, queryObj } = parseRequest(loaderContext.resource)
71
140
  const extraOptions = {
@@ -75,7 +144,7 @@ function getRequireScript ({ script, ctorType, loaderContext }) {
75
144
  ctorType,
76
145
  lang: script.lang || 'js'
77
146
  }
78
- content += ` ${getRequire('script', script, extraOptions)}\n`
147
+ content += `${getRequire('script', script, extraOptions)}\n`
79
148
  return content
80
149
  }
81
150
 
@@ -104,17 +173,11 @@ global.__mpxOptionsMap = {}
104
173
  global.__mpxPagesMap = {}
105
174
  global.__style = ${JSON.stringify(jsonConfig.style || 'v1')}
106
175
  global.__mpxPageConfig = ${JSON.stringify(jsonConfig.window)}
107
- global.__getAppComponents = function () {
108
- return ${shallowStringify(componentsMap)}
109
- }
110
- global.currentInject.getPages = function () {
111
- return ${shallowStringify(pagesMap)}
112
- }
176
+ global.__appComponentsMap = ${shallowStringify(componentsMap)}
177
+ global.__preloadRule = ${JSON.stringify(jsonConfig.preloadRule)}
178
+ global.currentInject.pagesMap = ${shallowStringify(pagesMap)}
113
179
  global.currentInject.firstPage = ${JSON.stringify(firstPage)}\n`
114
180
  } else {
115
- if (!hasApp) {
116
- content += ' global.__mpxGenericsMap = global.__mpxGenericsMap || {}\n'
117
- }
118
181
  if (ctorType === 'page') {
119
182
  const pageConfig = Object.assign({}, jsonConfig)
120
183
  delete pageConfig.usingComponents
@@ -122,19 +185,15 @@ global.currentInject.firstPage = ${JSON.stringify(firstPage)}\n`
122
185
  }
123
186
 
124
187
  content += `
125
-
126
- function getComponents() {
127
- return ${shallowStringify(componentsMap)}
128
- }
129
-
130
- global.currentInject.getComponents = getComponents\n`
188
+ var componentsMap = ${shallowStringify(componentsMap)}
189
+ global.currentInject.componentsMap = componentsMap\n`
131
190
  if (genericsInfo) {
191
+ if (!hasApp) {
192
+ content += 'global.__mpxGenericsMap = global.__mpxGenericsMap || {}\n'
193
+ }
132
194
  content += `
133
- const genericHash = ${JSON.stringify(genericsInfo.hash)}\n
134
- global.__mpxGenericsMap[genericHash] = function (name) {
135
- return getComponents()[name]
136
- }
137
- \n`
195
+ const genericHash = ${JSON.stringify(genericsInfo.hash)}\n
196
+ global.__mpxGenericsMap[genericHash] = componentsMap\n`
138
197
  }
139
198
  if (ctorType === 'component') {
140
199
  content += `global.currentInject.componentPath = '/' + ${JSON.stringify(outputPath)}\n`