@mpxjs/webpack-plugin 2.6.114-alpha.8 → 2.6.115

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 (129) hide show
  1. package/README.md +1 -1
  2. package/lib/built-in-loader.js +49 -0
  3. package/lib/config.js +0 -14
  4. package/lib/content-loader.js +13 -0
  5. package/lib/dependency/ChildCompileDependency.js +24 -0
  6. package/lib/dependency/InjectDependency.js +26 -0
  7. package/lib/dependency/RemovedModuleDependency.js +23 -0
  8. package/lib/{dependencies → dependency}/ReplaceDependency.js +2 -19
  9. package/lib/dependency/ResolveDependency.js +49 -0
  10. package/lib/extractor.js +178 -82
  11. package/lib/file-loader.js +19 -7
  12. package/lib/helpers.js +334 -39
  13. package/lib/index.js +525 -889
  14. package/lib/json-compiler/index.js +451 -245
  15. package/lib/json-compiler/{theme.js → theme-loader.js} +3 -5
  16. package/lib/loader.js +241 -178
  17. package/lib/native-loader.js +133 -71
  18. package/lib/parser.js +2 -1
  19. package/lib/path-loader.js +3 -0
  20. package/lib/platform/json/wx/index.js +1 -1
  21. package/lib/platform/template/normalize-component-rules.js +3 -2
  22. package/lib/platform/template/wx/component-config/button.js +2 -14
  23. package/lib/platform/template/wx/component-config/image.js +0 -4
  24. package/lib/platform/template/wx/component-config/input.js +0 -4
  25. package/lib/platform/template/wx/component-config/rich-text.js +0 -4
  26. package/lib/platform/template/wx/component-config/scroll-view.js +0 -4
  27. package/lib/platform/template/wx/component-config/switch.js +0 -4
  28. package/lib/platform/template/wx/component-config/text.js +0 -4
  29. package/lib/platform/template/wx/component-config/textarea.js +0 -5
  30. package/lib/platform/template/wx/component-config/view.js +0 -4
  31. package/lib/platform/template/wx/index.js +3 -149
  32. package/lib/plugin-loader.js +287 -0
  33. package/lib/resolver/AddEnvPlugin.js +3 -4
  34. package/lib/resolver/AddModePlugin.js +3 -4
  35. package/lib/resolver/PackageEntryPlugin.js +36 -23
  36. package/lib/runtime/base.styl +0 -5
  37. package/lib/runtime/components/web/getInnerListeners.js +3 -1
  38. package/lib/runtime/components/web/mpx-image.vue +5 -20
  39. package/lib/runtime/components/web/mpx-movable-view.vue +2 -6
  40. package/lib/runtime/components/web/mpx-swiper.vue +3 -18
  41. package/lib/runtime/i18n.wxs +11 -31
  42. package/lib/runtime/optionProcessor.js +3 -48
  43. package/lib/selector.js +10 -29
  44. package/lib/staticConfig.js +4 -0
  45. package/lib/style-compiler/index.js +24 -16
  46. package/lib/style-compiler/load-postcss-config.js +1 -3
  47. package/lib/style-compiler/plugins/conditional-strip.js +65 -68
  48. package/lib/style-compiler/plugins/rpx.js +37 -43
  49. package/lib/style-compiler/plugins/scope-id.js +72 -79
  50. package/lib/style-compiler/plugins/trans-special.js +18 -25
  51. package/lib/style-compiler/plugins/trim.js +7 -13
  52. package/lib/style-compiler/plugins/vw.js +16 -22
  53. package/lib/template-compiler/compiler.js +199 -106
  54. package/lib/template-compiler/index.js +139 -52
  55. package/lib/template-compiler/trans-dynamic-class-expr.js +13 -18
  56. package/lib/url-loader.js +29 -11
  57. package/lib/utils/add-query.js +1 -1
  58. package/lib/utils/get-main-compilation.js +6 -0
  59. package/lib/utils/is-url-request.js +1 -10
  60. package/lib/utils/match-condition.js +1 -4
  61. package/lib/utils/normalize.js +15 -4
  62. package/lib/utils/parse-request.js +3 -3
  63. package/lib/utils/read-json-for-src.js +34 -0
  64. package/lib/utils/stringify-query.js +0 -4
  65. package/lib/utils/try-require.js +16 -0
  66. package/lib/web/processJSON.js +144 -113
  67. package/lib/web/processScript.js +34 -47
  68. package/lib/web/processTemplate.js +40 -57
  69. package/lib/wxml/{loader.js → wxml-loader.js} +62 -21
  70. package/lib/wxs/WxsParserPlugin.js +2 -2
  71. package/lib/wxs/WxsPlugin.js +8 -4
  72. package/lib/wxs/WxsTemplatePlugin.js +92 -46
  73. package/lib/wxs/{i18n-loader.js → wxs-i18n-loader.js} +4 -5
  74. package/lib/wxs/wxs-loader.js +117 -0
  75. package/lib/wxs/{pre-loader.js → wxs-pre-loader.js} +5 -20
  76. package/lib/wxss/getImportPrefix.js +30 -0
  77. package/lib/wxss/loader.js +43 -31
  78. package/lib/wxss/localsLoader.js +5 -1
  79. package/lib/wxss/processCss.js +103 -107
  80. package/package.json +18 -21
  81. package/LICENSE +0 -433
  82. package/lib/dependencies/AddEntryDependency.js +0 -24
  83. package/lib/dependencies/AppEntryDependency.js +0 -58
  84. package/lib/dependencies/CommonJsAsyncDependency.js +0 -51
  85. package/lib/dependencies/CommonJsVariableDependency.js +0 -81
  86. package/lib/dependencies/DynamicEntryDependency.js +0 -171
  87. package/lib/dependencies/FlagPluginDependency.js +0 -24
  88. package/lib/dependencies/InjectDependency.js +0 -43
  89. package/lib/dependencies/RecordGlobalComponentsDependency.js +0 -50
  90. package/lib/dependencies/RecordIndependentDependency.js +0 -44
  91. package/lib/dependencies/RecordResourceMapDependency.js +0 -62
  92. package/lib/dependencies/RemoveEntryDependency.js +0 -40
  93. package/lib/dependencies/ResolveDependency.js +0 -88
  94. package/lib/independent-loader.js +0 -52
  95. package/lib/json-compiler/helper.js +0 -156
  96. package/lib/json-compiler/plugin.js +0 -150
  97. package/lib/partial-compile/index.js +0 -35
  98. package/lib/record-loader.js +0 -11
  99. package/lib/resolve-loader.js +0 -6
  100. package/lib/resolver/FixDescriptionInfoPlugin.js +0 -28
  101. package/lib/runtime/components/tenon/getInnerListeners.js +0 -317
  102. package/lib/runtime/components/tenon/tenon-button.vue +0 -305
  103. package/lib/runtime/components/tenon/tenon-image.vue +0 -61
  104. package/lib/runtime/components/tenon/tenon-input.vue +0 -99
  105. package/lib/runtime/components/tenon/tenon-rich-text.vue +0 -21
  106. package/lib/runtime/components/tenon/tenon-scroll-view.vue +0 -124
  107. package/lib/runtime/components/tenon/tenon-switch.vue +0 -91
  108. package/lib/runtime/components/tenon/tenon-text-area.vue +0 -64
  109. package/lib/runtime/components/tenon/tenon-text.vue +0 -64
  110. package/lib/runtime/components/tenon/tenon-view.vue +0 -93
  111. package/lib/runtime/components/tenon/util.js +0 -44
  112. package/lib/runtime/optionProcessor.tenon.js +0 -386
  113. package/lib/style-compiler/plugins/hm.js +0 -20
  114. package/lib/tenon/index.js +0 -105
  115. package/lib/tenon/processJSON.js +0 -360
  116. package/lib/tenon/processScript.js +0 -260
  117. package/lib/tenon/processStyles.js +0 -21
  118. package/lib/tenon/processTemplate.js +0 -133
  119. package/lib/utils/const.js +0 -10
  120. package/lib/utils/emit-file.js +0 -10
  121. package/lib/utils/eval-json-js.js +0 -31
  122. package/lib/utils/get-entry-name.js +0 -13
  123. package/lib/utils/get-json-content.js +0 -42
  124. package/lib/utils/get-relative-path.js +0 -24
  125. package/lib/utils/resolve.js +0 -13
  126. package/lib/utils/set.js +0 -47
  127. package/lib/utils/stringify-loaders-resource.js +0 -25
  128. package/lib/wxs/WxsModuleIdsPlugin.js +0 -29
  129. package/lib/wxs/loader.js +0 -142
@@ -1,8 +1,9 @@
1
1
  const templateCompiler = require('../template-compiler/compiler')
2
2
  const genComponentTag = require('../utils/gen-component-tag')
3
3
  const addQuery = require('../utils/add-query')
4
+ const path = require('path')
4
5
  const parseRequest = require('../utils/parse-request')
5
- // const { matchCondition } = require('../utils/match-condition')
6
+ const getMainCompilation = require('../utils/get-main-compilation')
6
7
 
7
8
  function calculateRootEleChild (arr) {
8
9
  if (!arr) {
@@ -20,30 +21,19 @@ function calculateRootEleChild (arr) {
20
21
  }, 0)
21
22
  }
22
23
 
23
- module.exports = function (template, {
24
- loaderContext,
25
- // hasScoped,
26
- hasComment,
27
- isNative,
28
- srcMode,
29
- moduleId,
30
- ctorType,
31
- usingComponents,
32
- componentGenerics
33
- }, callback) {
34
- const mpx = loaderContext.getMpx()
35
- const {
36
- mode,
37
- defs,
38
- wxsContentMap,
39
- decodeHTMLText,
40
- externalClasses,
41
- checkUsingComponents
42
- // autoVirtualHostRules
43
- } = mpx
44
- const { resourcePath } = parseRequest(loaderContext.resource)
24
+ module.exports = function (template, options, callback) {
25
+ const mode = options.mode
26
+ const srcMode = options.srcMode
27
+ const defs = options.defs
28
+ const moduleId = options.moduleId
29
+ const loaderContext = options.loaderContext
30
+ const ctorType = options.ctorType
31
+ const resourcePath = parseRequest(loaderContext.resource).resourcePath
45
32
  const builtInComponentsMap = {}
46
-
33
+ const compilation = loaderContext._compilation
34
+ const mainCompilation = getMainCompilation(compilation)
35
+ const mpx = mainCompilation.__mpx__
36
+ const wxsContentMap = mpx.wxsContentMap
47
37
  let wxsModuleMap, genericsInfo
48
38
  let output = '/* template */\n'
49
39
 
@@ -53,7 +43,7 @@ module.exports = function (template, {
53
43
  content: '<div class="app"><mpx-keep-alive><router-view class="page"></router-view></mpx-keep-alive></div>'
54
44
  }
55
45
  builtInComponentsMap['mpx-keep-alive'] = {
56
- resource: addQuery('@mpxjs/webpack-plugin/lib/runtime/components/web/mpx-keep-alive.vue', { isComponent: true })
46
+ resource: addQuery('@mpxjs/webpack-plugin/lib/runtime/components/web/mpx-keep-alive.vue', { component: true })
57
47
  }
58
48
  }
59
49
 
@@ -72,7 +62,7 @@ module.exports = function (template, {
72
62
  }
73
63
  if (template.content) {
74
64
  const templateSrcMode = template.mode || srcMode
75
- const { root, meta } = templateCompiler.parse(template.content, {
65
+ const parsed = templateCompiler.parse(template.content, {
76
66
  warn: (msg) => {
77
67
  loaderContext.emitWarning(
78
68
  new Error('[template compiler][' + loaderContext.resource + ']: ' + msg)
@@ -83,59 +73,52 @@ module.exports = function (template, {
83
73
  new Error('[template compiler][' + loaderContext.resource + ']: ' + msg)
84
74
  )
85
75
  },
86
- usingComponents,
87
- hasComment,
88
- isNative,
76
+ usingComponents: options.usingComponents,
77
+ hasComment: options.hasComment,
78
+ isNative: options.isNative,
79
+ basename: path.basename(resourcePath),
89
80
  isComponent: ctorType === 'component',
90
81
  mode,
91
82
  srcMode: templateSrcMode,
92
83
  defs,
93
- decodeHTMLText,
94
- externalClasses,
95
- // todo 后续输出web也采用mpx的scoped处理
84
+ decodeHTMLText: options.decodeHTMLText,
85
+ externalClasses: options.externalClasses,
96
86
  hasScoped: false,
97
87
  moduleId,
98
- filePath: resourcePath,
88
+ filePath: loaderContext.resourcePath,
99
89
  i18n: null,
100
- checkUsingComponents,
90
+ checkUsingComponents: options.checkUsingComponents,
101
91
  // web模式下全局组件不会被合入usingComponents中,故globalComponents可以传空
102
92
  globalComponents: [],
103
93
  // web模式下实现抽象组件
104
- componentGenerics
105
- // todo 后续输出web也基于autoVirtualHostRules决定是否添加root wrapper
106
- // hasVirtualHost: matchCondition(resourcePath, autoVirtualHostRules)
94
+ componentGenerics: options.componentGenerics
107
95
  })
108
- if (meta.wxsModuleMap) {
109
- wxsModuleMap = meta.wxsModuleMap
96
+ if (parsed.meta.wxsModuleMap) {
97
+ wxsModuleMap = parsed.meta.wxsModuleMap
110
98
  }
111
- if (meta.wxsContentMap) {
112
- for (let module in meta.wxsContentMap) {
113
- wxsContentMap[`${resourcePath}~${module}`] = meta.wxsContentMap[module]
99
+ if (parsed.meta.wxsContentMap) {
100
+ for (let module in parsed.meta.wxsContentMap) {
101
+ wxsContentMap[`${resourcePath}~${module}`] = parsed.meta.wxsContentMap[module]
114
102
  }
115
103
  }
116
- if (meta.builtInComponentsMap) {
117
- Object.keys(meta.builtInComponentsMap).forEach((name) => {
104
+ if (parsed.meta.builtInComponentsMap) {
105
+ Object.keys(parsed.meta.builtInComponentsMap).forEach((name) => {
118
106
  builtInComponentsMap[name] = {
119
- resource: addQuery(meta.builtInComponentsMap[name], { isComponent: true })
107
+ resource: addQuery(parsed.meta.builtInComponentsMap[name], { component: true })
120
108
  }
121
109
  })
122
110
  }
123
- if (meta.genericsInfo) {
124
- genericsInfo = meta.genericsInfo
111
+ if (parsed.meta.genericsInfo) {
112
+ genericsInfo = parsed.meta.genericsInfo
125
113
  }
126
- // 输出H5有多个root element时, 使用mpx-root-view标签包裹
127
- // todo 后续输出web也基于autoVirtualHostRules决定是否添加root wrapper
128
- if (root.tag === 'temp-node') {
129
- const childLen = calculateRootEleChild(root.children)
114
+ // 输出H5有多个root element时, 使用div标签包裹
115
+ if (parsed.root.tag === 'temp-node') {
116
+ const childLen = calculateRootEleChild(parsed.root.children)
130
117
  if (childLen >= 2) {
131
- root.tag = 'div'
132
- templateCompiler.addAttrs(root, [{
133
- name: 'class',
134
- value: 'mpx-root-view'
135
- }])
118
+ parsed.root.tag = 'div'
136
119
  }
137
120
  }
138
- return templateCompiler.serialize(root)
121
+ return templateCompiler.serialize(parsed.root)
139
122
  }
140
123
  })
141
124
  output += '\n\n'
@@ -1,9 +1,12 @@
1
+ // const htmlMinifier = require('html-minifier')
1
2
  const attrParse = require('./attributesParser')
2
3
  const loaderUtils = require('loader-utils')
3
4
  const url = require('url')
4
5
  const config = require('../config')
6
+ const getMainCompilation = require('../utils/get-main-compilation')
5
7
  const createHelpers = require('../helpers')
6
8
  const isUrlRequest = require('../utils/is-url-request')
9
+ const addQuery = require('../utils/add-query')
7
10
  const parseRequest = require('../utils/parse-request')
8
11
 
9
12
  function randomIdent () {
@@ -11,21 +14,39 @@ function randomIdent () {
11
14
  }
12
15
 
13
16
  module.exports = function (content) {
17
+ const loaderContext = this
18
+ const isProduction = this.minimize || process.env.NODE_ENV === 'production'
14
19
  const options = loaderUtils.getOptions(this) || {}
15
- const mpx = this.getMpx()
16
- const root = mpx.projectRoot
17
- const externals = mpx.externals
20
+ const mpx = getMainCompilation(this._compilation).__mpx__
18
21
 
19
- const { queryObj } = parseRequest(this.resource)
22
+ const { resourcePath: filePath, queryObj } = parseRequest(this.resource)
23
+ const moduleId = 'm' + mpx.pathHash(filePath)
20
24
  const hasScoped = false
21
25
  const hasComment = false
22
26
  const isNative = true
23
27
 
28
+ const usingComponents = []
29
+
24
30
  const mode = mpx.mode
31
+ const globalSrcMode = mpx.srcMode
25
32
  const localSrcMode = queryObj.mode
33
+ const srcMode = localSrcMode || globalSrcMode
26
34
  const customAttributes = options.attributes || mpx.attributes || []
27
35
 
28
- const { getRequestString } = createHelpers(this)
36
+ const {
37
+ getSrcRequestString
38
+ } = createHelpers({
39
+ loaderContext,
40
+ options,
41
+ moduleId,
42
+ isProduction,
43
+ hasScoped,
44
+ hasComment,
45
+ usingComponents,
46
+ srcMode,
47
+ isNative,
48
+ projectRoot: options.root || ''
49
+ })
29
50
 
30
51
  const attributes = ['image:src', 'audio:src', 'video:src', 'cover-image:src', 'import:src', 'include:src', `${config[mode].wxs.tag}:${config[mode].wxs.src}`].concat(customAttributes)
31
52
 
@@ -43,7 +64,7 @@ module.exports = function (content) {
43
64
  const data = {}
44
65
  content = [content]
45
66
  links.forEach(function (link) {
46
- if (!isUrlRequest(link.value, root, externals)) return
67
+ if (!isUrlRequest(link.value, options.root)) return
47
68
 
48
69
  if (link.value.indexOf('mailto:') > -1) return
49
70
 
@@ -67,37 +88,57 @@ module.exports = function (content) {
67
88
  })
68
89
  content.reverse()
69
90
  content = content.join('')
91
+
92
+ // if (isProduction) {
93
+ // const minimizeOptions = Object.assign({}, options);
94
+ // [
95
+ // 'removeComments',
96
+ // 'removeCommentsFromCDATA',
97
+ // 'removeCDATASectionsFromCDATA',
98
+ // 'caseSensitive',
99
+ // 'collapseWhitespace',
100
+ // 'conservativeCollapse',
101
+ // 'useShortDoctype',
102
+ // 'keepClosingSlash',
103
+ // 'removeScriptTypeAttributes',
104
+ // 'removeStyleTypeAttributes'
105
+ // ].forEach(function (name) {
106
+ // if (typeof minimizeOptions[name] === 'undefined') {
107
+ // minimizeOptions[name] = true
108
+ // }
109
+ // })
110
+ //
111
+ // const KEY_IGNORECUSTOM_FRAGMENTS = 'ignoreCustomFragments'
112
+ // if (typeof minimizeOptions[KEY_IGNORECUSTOM_FRAGMENTS] === 'undefined') {
113
+ // minimizeOptions[KEY_IGNORECUSTOM_FRAGMENTS] = [/{{[\s\S]*?}}/]
114
+ // }
115
+ //
116
+ // content = htmlMinifier.minify(content, minimizeOptions)
117
+ // }
118
+
70
119
  content = JSON.stringify(content)
71
120
 
72
121
  const exportsString = 'module.exports = '
73
122
 
74
- return exportsString + content.replace(/xxxHTMLLINKxxx[0-9.]+xxx/g, (match) => {
123
+ return exportsString + content.replace(/xxxHTMLLINKxxx[0-9.]+xxx/g, function (match) {
75
124
  if (!data[match]) return match
76
125
 
77
126
  const link = data[match]
78
127
 
79
- let src = loaderUtils.urlToRequest(link.value, root)
128
+ let src = loaderUtils.urlToRequest(link.value, options.root)
129
+ src = addQuery(src, { isStatic: true })
80
130
 
81
- let requestString, extraOptions
131
+ let requestString
82
132
 
83
133
  switch (link.tag) {
84
134
  case 'import':
85
135
  case 'include':
86
- extraOptions = {
87
- hasScoped,
88
- hasComment,
89
- isNative,
90
- isStatic: true
91
- }
92
- requestString = getRequestString('template', { src, mode: localSrcMode }, extraOptions)
136
+ requestString = getSrcRequestString('template', { src, mode: localSrcMode }, -1)
93
137
  break
94
138
  case config[mode].wxs.tag:
95
139
  // 显式传递issuerResource避免模块缓存以及提供给wxs-loader计算相对路径
96
- extraOptions = {
97
- issuerResource: this.resource,
98
- isStatic: true
99
- }
100
- requestString = getRequestString('wxs', { src, mode: localSrcMode }, extraOptions)
140
+ src = addQuery(src, { issuerResource: loaderContext.resource })
141
+ requestString = getSrcRequestString('wxs', { src, mode: localSrcMode }, -1, undefined, '!!')
101
142
  break
102
143
  default:
103
144
  requestString = JSON.stringify(src)
@@ -3,11 +3,11 @@ class WxsParserPlugin {
3
3
  this.options = options
4
4
  }
5
5
 
6
- apply (parser) {
6
+ apply (parser, compilation) {
7
7
  parser.hooks.program.tap({
8
8
  name: 'WxsParserPlugin',
9
9
  // 放在最后面执行
10
- stage: 1000
10
+ stage: 100
11
11
  }, ast => {
12
12
  const module = parser.state.module
13
13
  if (module.buildInfo) {
@@ -1,6 +1,5 @@
1
1
  const WxsTemplatePlugin = require('./WxsTemplatePlugin')
2
2
  const WxsParserPlugin = require('./WxsParserPlugin')
3
- const WxsModuleIdsPlugin = require('./WxsModuleIdsPlugin')
4
3
 
5
4
  class WxsPlugin {
6
5
  constructor (options = { mode: 'wx' }) {
@@ -9,15 +8,20 @@ class WxsPlugin {
9
8
 
10
9
  apply (compiler) {
11
10
  compiler.hooks.thisCompilation.tap('WxsPlugin', (compilation, { normalModuleFactory }) => {
12
- new WxsTemplatePlugin(this.options).apply(compilation)
13
- new WxsModuleIdsPlugin(this.options).apply(compilation)
11
+ new WxsTemplatePlugin(this.options).apply(
12
+ compilation.mainTemplate,
13
+ compilation
14
+ )
14
15
 
15
16
  compilation.hooks.buildModule.tap('WxsPlugin', (module) => {
16
17
  module.wxs = true
17
18
  })
18
19
 
19
20
  const handler = (parser) => {
20
- new WxsParserPlugin(this.options).apply(parser)
21
+ new WxsParserPlugin(this.options).apply(
22
+ parser,
23
+ compilation
24
+ )
21
25
  }
22
26
 
23
27
  normalModuleFactory.hooks.parser
@@ -1,58 +1,104 @@
1
+ const Template = require('webpack/lib/Template')
1
2
  const config = require('../config')
2
- const { ConcatSource } = require('webpack').sources
3
- const JavascriptModulesPlugin = require('webpack/lib/javascript/JavascriptModulesPlugin')
3
+ const { ConcatSource } = require('webpack-sources')
4
4
 
5
- module.exports = class WxsTemplatePlugin {
5
+ module.exports = class WxsMainTemplatePlugin {
6
6
  constructor (options = { mode: 'wx' }) {
7
7
  this.options = options
8
8
  }
9
9
 
10
- apply (compilation) {
11
- const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation)
12
-
13
- hooks.renderStartup.tap('WxsTemplatePlugin', (source) => {
14
- const postfix = 'return __webpack_exports__ && __webpack_exports__.__esModule? __webpack_exports__["default"] : __webpack_exports__;\n'
15
- return new ConcatSource(source, postfix)
10
+ apply (mainTemplate, compilation) {
11
+ mainTemplate.hooks.require.tap('MainTemplate', (source, chunk, hash) => {
12
+ return Template.asString([
13
+ '// Check if module is in cache',
14
+ 'if(installedModules[moduleId]) {',
15
+ Template.indent('return installedModules[moduleId].exports;'),
16
+ '}',
17
+ '// Create a new module (and put it into the cache)',
18
+ 'var module = installedModules[moduleId] = {',
19
+ Template.indent(mainTemplate.hooks.moduleObj.call('', chunk, hash, 'moduleId')),
20
+ '};',
21
+ '',
22
+ Template.asString(
23
+ [
24
+ '// Execute the module function',
25
+ '// wxs连call都不支持我也是服气...',
26
+ `modules[moduleId](module, module.exports, ${mainTemplate.renderRequireFunctionForModule(
27
+ hash,
28
+ chunk,
29
+ 'moduleId'
30
+ )});`
31
+ ]
32
+ ),
33
+ '',
34
+ '// Flag the module as loaded',
35
+ 'module.l = true;',
36
+ '',
37
+ '// Return the exports of the module',
38
+ 'return module.exports;'
39
+ ])
16
40
  })
41
+ mainTemplate.hooks.requireExtensions.tap(
42
+ 'WxsMainTemplatePlugin',
43
+ () => {
44
+ return Template.asString([
45
+ '// define harmony function exports',
46
+ `${mainTemplate.requireFn}.d = function(exports, name, getter) {`,
47
+ Template.indent([
48
+ 'exports[name] = getter();'
49
+ ]),
50
+ '};',
51
+ '',
52
+ '// define __esModule on exports',
53
+ `${mainTemplate.requireFn}.r = function(exports) {`,
54
+ Template.indent([
55
+ 'exports.__esModule = true;'
56
+ ]),
57
+ '};',
58
+ '',
59
+ '// getDefaultExport function for compatibility with non-harmony modules',
60
+ mainTemplate.requireFn + '.n = function(module) {',
61
+ Template.indent([
62
+ 'var getter = module && module.__esModule ?',
63
+ Template.indent([
64
+ 'function getDefault() { return module["default"]; } :',
65
+ 'function getModuleExports() { return module; };'
66
+ ]),
67
+ `getter.a = getter();`,
68
+ 'return getter;'
69
+ ]),
70
+ '};'
71
+ ])
72
+ }
73
+ )
74
+ mainTemplate.hooks.renderWithEntry.tap(
75
+ 'WxsMainTemplatePlugin',
76
+ (source, chunk, hash) => {
77
+ const prefix = config[this.options.mode].wxs.templatePrefix
78
+ return new ConcatSource(prefix, source)
79
+ }
80
+ )
17
81
 
18
- hooks.render.tap('WxsTemplatePlugin', (source) => {
19
- const prefix = config[this.options.mode].wxs.templatePrefix
20
- return new ConcatSource(prefix, source)
82
+ mainTemplate.hooks.startup.tap('MainTemplate', (source, chunk, hash) => {
83
+ /** @type {string[]} */
84
+ const buf = []
85
+ if (chunk.entryModule) {
86
+ buf.push('// Load entry module and return exports')
87
+ buf.push(
88
+ `var entryExports = ${mainTemplate.renderRequireFunctionForModule(
89
+ hash,
90
+ chunk,
91
+ JSON.stringify(chunk.entryModule.id)
92
+ )}(${mainTemplate.requireFn}.s = ${JSON.stringify(chunk.entryModule.id)});`
93
+ )
94
+ buf.push('return entryExports && entryExports.__esModule? entryExports["default"] : entryExports;')
95
+ }
96
+ return Template.asString(buf)
21
97
  })
22
98
 
23
- // todo webpack5的新的代码生成模式下完美支持.d.r.n的成本较高,暂不处理,wxs暂时只支持wx源码形式
24
- // mainTemplate.hooks.requireExtensions.tap(
25
- // 'WxsMainTemplatePlugin',
26
- // () => {
27
- // return Template.asString([
28
- // '// define harmony function exports',
29
- // `${mainTemplate.requireFn}.d = function(exports, name, getter) {`,
30
- // Template.indent([
31
- // 'exports[name] = getter();'
32
- // ]),
33
- // '};',
34
- // '',
35
- // '// define __esModule on exports',
36
- // `${mainTemplate.requireFn}.r = function(exports) {`,
37
- // Template.indent([
38
- // 'exports.__esModule = true;'
39
- // ]),
40
- // '};',
41
- // '',
42
- // '// getDefaultExport function for compatibility with non-harmony modules',
43
- // mainTemplate.requireFn + '.n = function(module) {',
44
- // Template.indent([
45
- // 'var getter = module && module.__esModule ?',
46
- // Template.indent([
47
- // 'function getDefault() { return module["default"]; } :',
48
- // 'function getModuleExports() { return module; };'
49
- // ]),
50
- // `getter.a = getter();`,
51
- // 'return getter;'
52
- // ]),
53
- // '};'
54
- // ])
55
- // }
56
- // )
99
+ mainTemplate.hooks.hash.tap('WxsMainTemplatePlugin', hash => {
100
+ hash.update('wxs')
101
+ hash.update(this.options.mode)
102
+ })
57
103
  }
58
104
  }
@@ -1,9 +1,11 @@
1
1
  // 该loader用于将用户定义的messages注入到i18n.wxs中
2
+ const getMainCompilation = require('../utils/get-main-compilation')
2
3
  const loaderUtils = require('loader-utils')
3
4
 
4
5
  module.exports = function (content) {
5
- const i18n = this.getMpx().i18n
6
- let prefix = 'var __mpx_messages__, __mpx_datetime_formats__, __mpx_number_formats__, __mpx_locale__\n'
6
+ const mainCompilation = getMainCompilation(this._compilation)
7
+ const i18n = mainCompilation.__mpx__.i18n
8
+ let prefix = 'var __mpx_messages__, __mpx_datetime_formats__, __mpx_number_formats__\n'
7
9
  if (i18n) {
8
10
  if (i18n.messages) {
9
11
  prefix += `__mpx_messages__ = ${JSON.stringify(i18n.messages)}\n`
@@ -20,9 +22,6 @@ module.exports = function (content) {
20
22
  } else if (i18n.numberFormatsPath) {
21
23
  prefix += `__mpx_number_formats__ = require(${loaderUtils.stringifyRequest(this, i18n.numberFormatsPath)})\n`
22
24
  }
23
- if (i18n.locale) {
24
- prefix += `__mpx_locale__ = ${JSON.stringify(i18n.locale)}\n`
25
- }
26
25
  }
27
26
  content = prefix + content
28
27
  return content
@@ -0,0 +1,117 @@
1
+ const NodeTargetPlugin = require('webpack/lib/node/NodeTargetPlugin')
2
+ const SingleEntryPlugin = require('webpack/lib/SingleEntryPlugin')
3
+ const LimitChunkCountPlugin = require('webpack/lib/optimize/LimitChunkCountPlugin')
4
+ const path = require('path')
5
+ const WxsPlugin = require('./WxsPlugin')
6
+ const ChildCompileDependency = require('../dependency/ChildCompileDependency')
7
+ const getMainCompilation = require('../utils/get-main-compilation')
8
+ const parseRequest = require('../utils/parse-request')
9
+ const toPosix = require('../utils/to-posix')
10
+ const fixRelative = require('../utils/fix-relative')
11
+ const config = require('../config')
12
+
13
+ module.exports = function () {
14
+ const nativeCallback = this.async()
15
+ const mainCompilation = getMainCompilation(this._compilation)
16
+ const mpx = mainCompilation.__mpx__
17
+ const assetsInfo = mpx.assetsInfo
18
+ const mode = mpx.mode
19
+ const wxsMap = mpx.wxsMap
20
+ const getOutputPath = mpx.getOutputPath
21
+ const rootName = mainCompilation._preparedEntrypoints[0].name
22
+ let { resourcePath, queryObj } = parseRequest(this.resource)
23
+ const { resourcePath: issuerResourcePath, queryObj: issuerQueryObj } = parseRequest(queryObj.issuerResource || this._module.issuer.resource)
24
+ const issuerPackageName = issuerQueryObj.packageRoot || mpx.currentPackageRoot || 'main'
25
+ const pagesMap = mpx.pagesMap
26
+ const componentsMap = mpx.componentsMap[issuerPackageName]
27
+ const staticResourcesMap = mpx.staticResourcesMap[issuerPackageName]
28
+ const issuerName = pagesMap[issuerResourcePath] || componentsMap[issuerResourcePath] || staticResourcesMap[issuerResourcePath] || rootName
29
+ const issuerDir = path.dirname(issuerName)
30
+
31
+ const getName = (raw) => {
32
+ const match = /^(.*?)(\.[^.]*)?$/.exec(raw)
33
+ return match[1]
34
+ }
35
+
36
+ const wxsModule = queryObj.wxsModule
37
+ if (wxsModule) {
38
+ resourcePath = `${resourcePath}~${wxsModule}`
39
+ }
40
+ const packageRoot = queryObj.packageRoot || ''
41
+ const ext = config[mode].wxs.ext
42
+ let filename = toPosix(path.join(packageRoot, getOutputPath(resourcePath, ext.slice(1), { ext })))
43
+
44
+ filename = mpx.getPackageInfo({
45
+ resource: this.resource,
46
+ outputPath: filename,
47
+ resourceType: 'staticResources',
48
+ warn: (err) => {
49
+ this.emitWarning(err)
50
+ }
51
+ }).outputPath
52
+
53
+ const callback = (err) => {
54
+ if (err) return nativeCallback(err)
55
+ let relativePath = toPosix(path.relative(issuerDir, filename))
56
+ relativePath = fixRelative(relativePath, mode)
57
+ nativeCallback(null, `module.exports = ${JSON.stringify(relativePath)};`)
58
+ }
59
+
60
+ if (wxsMap[filename]) {
61
+ wxsMap[filename].modules.push(this._module)
62
+ return callback()
63
+ }
64
+
65
+ wxsMap[filename] = {
66
+ dep: null,
67
+ modules: [this._module]
68
+ }
69
+
70
+ const outputOptions = {
71
+ filename
72
+ }
73
+ // wxs文件必须经过pre-loader
74
+ const request = `!${this.remainingRequest}`
75
+ const plugins = [
76
+ new WxsPlugin({ mode }),
77
+ new NodeTargetPlugin(),
78
+ new SingleEntryPlugin(this.context, request, getName(filename)),
79
+ new LimitChunkCountPlugin({ maxChunks: 1 })
80
+ ]
81
+
82
+ const childCompiler = mainCompilation.createChildCompiler(request, outputOptions, plugins)
83
+
84
+ let entryModule
85
+ childCompiler.hooks.thisCompilation.tap('MpxWebpackPlugin ', (compilation) => {
86
+ compilation.hooks.succeedEntry.tap('MpxWebpackPlugin', (entry, name, module) => {
87
+ entryModule = module
88
+ const dep = new ChildCompileDependency(entryModule)
89
+ wxsMap[filename].dep = dep
90
+ })
91
+ })
92
+
93
+ childCompiler.hooks.afterCompile.tapAsync('MpxWebpackPlugin', (compilation, callback) => {
94
+ Object.keys(compilation.assets).forEach((name) => {
95
+ // 因为子编译会合并assetsInfo会互相覆盖,使用全局mpx对象收集完之后再合并到主assetsInfo中
96
+ const assetInfo = assetsInfo.get(name) || { modules: [] }
97
+ assetInfo.modules.push(entryModule)
98
+ assetsInfo.set(name, assetInfo)
99
+ })
100
+ callback()
101
+ })
102
+
103
+ childCompiler.runAsChild((err, entries, compilation) => {
104
+ if (err) return callback(err)
105
+ if (compilation.errors.length > 0) {
106
+ return callback(compilation.errors[0])
107
+ }
108
+
109
+ compilation.fileDependencies.forEach((dep) => {
110
+ this.addDependency(dep)
111
+ }, this)
112
+ compilation.contextDependencies.forEach((dep) => {
113
+ this.addContextDependency(dep)
114
+ }, this)
115
+ callback()
116
+ })
117
+ }