@mpxjs/webpack-plugin 2.6.110 → 2.7.0-beta.10

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 (72) hide show
  1. package/lib/dependencies/AppEntryDependency.js +56 -0
  2. package/lib/dependencies/CommonJsVariableDependency.js +69 -0
  3. package/lib/dependencies/DynamicEntryDependency.js +131 -0
  4. package/lib/dependencies/FlagPluginDependency.js +23 -0
  5. package/lib/dependencies/InjectDependency.js +43 -0
  6. package/lib/dependencies/RecordGlobalComponentsDependency.js +50 -0
  7. package/lib/dependencies/RecordResourceMapDependency.js +52 -0
  8. package/lib/dependencies/RemoveEntryDependency.js +40 -0
  9. package/lib/{dependency → dependencies}/ReplaceDependency.js +19 -2
  10. package/lib/dependencies/ResolveDependency.js +84 -0
  11. package/lib/extractor.js +73 -178
  12. package/lib/file-loader.js +7 -19
  13. package/lib/helpers.js +42 -330
  14. package/lib/index.js +497 -376
  15. package/lib/json-compiler/helper.js +148 -0
  16. package/lib/json-compiler/index.js +195 -439
  17. package/lib/json-compiler/plugin.js +150 -0
  18. package/lib/json-compiler/{theme-loader.js → theme.js} +5 -3
  19. package/lib/loader.js +107 -226
  20. package/lib/native-loader.js +65 -132
  21. package/lib/parser.js +1 -2
  22. package/lib/record-loader.js +11 -0
  23. package/lib/{path-loader.js → resolve-loader.js} +0 -0
  24. package/lib/resolver/AddEnvPlugin.js +3 -2
  25. package/lib/resolver/AddModePlugin.js +3 -2
  26. package/lib/runtime/base.styl +5 -0
  27. package/lib/runtime/i18n.wxs +3 -3
  28. package/lib/runtime/optionProcessor.js +3 -3
  29. package/lib/selector.js +9 -11
  30. package/lib/style-compiler/index.js +12 -19
  31. package/lib/template-compiler/compiler.js +21 -162
  32. package/lib/template-compiler/index.js +47 -136
  33. package/lib/url-loader.js +11 -29
  34. package/lib/utils/add-query.js +1 -1
  35. package/lib/utils/const.js +9 -0
  36. package/lib/utils/emit-file.js +10 -0
  37. package/lib/utils/eval-json-js.js +31 -0
  38. package/lib/utils/get-entry-name.js +13 -0
  39. package/lib/utils/get-json-content.js +41 -0
  40. package/lib/utils/is-url-request.js +10 -1
  41. package/lib/utils/normalize.js +0 -13
  42. package/lib/utils/parse-request.js +3 -3
  43. package/lib/utils/resolve.js +13 -0
  44. package/lib/utils/set.js +47 -0
  45. package/lib/utils/stringify-loaders-resource.js +25 -0
  46. package/lib/utils/stringify-query.js +4 -0
  47. package/lib/web/processJSON.js +113 -142
  48. package/lib/web/processScript.js +32 -26
  49. package/lib/web/processTemplate.js +57 -39
  50. package/lib/wxml/{wxml-loader.js → loader.js} +24 -60
  51. package/lib/wxs/WxsModuleIdsPlugin.js +32 -0
  52. package/lib/wxs/WxsParserPlugin.js +2 -2
  53. package/lib/wxs/WxsPlugin.js +4 -8
  54. package/lib/wxs/WxsTemplatePlugin.js +46 -92
  55. package/lib/wxs/{wxs-i18n-loader.js → i18n-loader.js} +1 -3
  56. package/lib/wxs/{wxs-loader.js → loader.js} +41 -50
  57. package/lib/wxs/{wxs-pre-loader.js → pre-loader.js} +3 -4
  58. package/lib/wxss/loader.js +31 -43
  59. package/lib/wxss/localsLoader.js +1 -5
  60. package/package.json +5 -9
  61. package/lib/built-in-loader.js +0 -49
  62. package/lib/content-loader.js +0 -13
  63. package/lib/dependency/ChildCompileDependency.js +0 -24
  64. package/lib/dependency/InjectDependency.js +0 -26
  65. package/lib/dependency/RemovedModuleDependency.js +0 -23
  66. package/lib/dependency/ResolveDependency.js +0 -49
  67. package/lib/plugin-loader.js +0 -287
  68. package/lib/staticConfig.js +0 -4
  69. package/lib/utils/get-main-compilation.js +0 -6
  70. package/lib/utils/read-json-for-src.js +0 -34
  71. package/lib/utils/try-require.js +0 -16
  72. package/lib/wxss/getImportPrefix.js +0 -30
@@ -2,7 +2,6 @@ const genComponentTag = require('../utils/gen-component-tag')
2
2
  const loaderUtils = require('loader-utils')
3
3
  const addQuery = require('../utils/add-query')
4
4
  const normalize = require('../utils/normalize')
5
- const builtInLoaderPath = normalize.lib('built-in-loader')
6
5
  const optionProcessorPath = normalize.lib('runtime/optionProcessor')
7
6
  const tabBarContainerPath = normalize.lib('runtime/components/web/mpx-tab-bar-container.vue')
8
7
  const tabBarPath = normalize.lib('runtime/components/web/mpx-tab-bar.vue')
@@ -21,24 +20,29 @@ function shallowStringify (obj) {
21
20
  return `{${arr.join(',')}}`
22
21
  }
23
22
 
24
- module.exports = function (script, options, callback) {
25
- const ctorType = options.ctorType
26
- const builtInComponentsMap = options.builtInComponentsMap
27
- const localComponentsMap = options.localComponentsMap
28
- const localPagesMap = options.localPagesMap
29
- const srcMode = options.srcMode
30
- const loaderContext = options.loaderContext
31
- const isProduction = options.isProduction
32
- const componentId = options.componentId
33
- const getRequireForSrc = options.getRequireForSrc
34
- const i18n = options.i18n
35
- const jsonConfig = options.jsonConfig
23
+ module.exports = function (script, {
24
+ loaderContext,
25
+ ctorType,
26
+ srcMode,
27
+ isProduction,
28
+ componentGenerics,
29
+ jsonConfig,
30
+ outputPath,
31
+ tabBarMap,
32
+ tabBarStr,
33
+ builtInComponentsMap,
34
+ genericsInfo,
35
+ wxsModuleMap,
36
+ localComponentsMap,
37
+ localPagesMap
38
+ }, callback) {
39
+ const mpx = loaderContext.getMpx()
40
+ const {
41
+ i18n,
42
+ projectRoot
43
+ } = mpx
44
+
36
45
  const tabBar = jsonConfig.tabBar
37
- const tabBarMap = options.tabBarMap
38
- const tabBarStr = options.tabBarStr
39
- const genericsInfo = options.genericsInfo
40
- const componentGenerics = options.componentGenerics
41
- const forceDisableBuiltInLoader = options.forceDisableBuiltInLoader
42
46
 
43
47
  const emitWarning = (msg) => {
44
48
  loaderContext.emitWarning(
@@ -50,7 +54,7 @@ module.exports = function (script, options, callback) {
50
54
  let tabBarPagesMap = {}
51
55
  if (tabBar && tabBarMap) {
52
56
  // 挂载tabBar组件
53
- const tabBarRequest = stringifyRequest(addQuery(tabBar.custom ? './custom-tab-bar/index' : tabBarPath, { component: true }))
57
+ const tabBarRequest = stringifyRequest(addQuery(tabBar.custom ? './custom-tab-bar/index' : tabBarPath, { isComponent: true }))
54
58
  tabBarPagesMap['mpx-tab-bar'] = `getComponent(require(${tabBarRequest}))`
55
59
  // 挂载tabBar页面
56
60
  Object.keys(tabBarMap).forEach((pagePath) => {
@@ -162,9 +166,9 @@ module.exports = function (script, options, callback) {
162
166
  }
163
167
  // 注入wxs模块
164
168
  content += ' const wxsModules = {}\n'
165
- if (options.wxsModuleMap) {
166
- Object.keys(options.wxsModuleMap).forEach((module) => {
167
- const src = loaderUtils.urlToRequest(options.wxsModuleMap[module], options.projectRoot)
169
+ if (wxsModuleMap) {
170
+ Object.keys(wxsModuleMap).forEach((module) => {
171
+ const src = loaderUtils.urlToRequest(wxsModuleMap[module], projectRoot)
168
172
  const expression = `require(${stringifyRequest(src)})`
169
173
  content += ` wxsModules.${module} = ${expression}\n`
170
174
  })
@@ -203,7 +207,7 @@ module.exports = function (script, options, callback) {
203
207
 
204
208
  Object.keys(builtInComponentsMap).forEach((componentName) => {
205
209
  const componentCfg = builtInComponentsMap[componentName]
206
- const componentRequest = forceDisableBuiltInLoader ? stringifyRequest(componentCfg.resource) : stringifyRequest('builtInComponent.vue!=!' + builtInLoaderPath + '!' + componentCfg.resource)
210
+ const componentRequest = stringifyRequest(componentCfg.resource)
207
211
  componentsMap[componentName] = `getComponent(require(${componentRequest}), { __mpxBuiltIn: true })`
208
212
  })
209
213
 
@@ -212,9 +216,11 @@ module.exports = function (script, options, callback) {
212
216
  content += ` global.currentResource = ${JSON.stringify(loaderContext.resourcePath)}\n`
213
217
  }
214
218
  // 为了正确获取currentSrcMode便于运行时进行转换,对于src引入的组件script采用require方式引入(由于webpack会将import的执行顺序上升至最顶),这意味着对于src引入脚本中的named export将不会生效,不过鉴于mpx和小程序中本身也没有在组件script中声明export的用法,所以应该没有影响
219
+ content += '\n\n\n/** ====== Source start ====== **/\n'
215
220
  content += script.src
216
- ? (getRequireForSrc('script', script) + '\n')
217
- : (script.content + '\n') + '\n'
221
+ ? `require(${stringifyRequest(script.src)})\n`
222
+ : script.content
223
+ content += '\n/** ====== Source end ====== **/\n\n\n'
218
224
  // createApp/Page/Component执行完成后立刻获取当前的option并暂存
219
225
  content += ` const currentOption = global.currentOption\n`
220
226
  // 获取pageConfig
@@ -245,7 +251,7 @@ module.exports = function (script, options, callback) {
245
251
  currentOption,
246
252
  ${JSON.stringify(ctorType)},
247
253
  ${JSON.stringify(firstPage)},
248
- ${JSON.stringify(componentId)},
254
+ ${JSON.stringify(outputPath)},
249
255
  ${JSON.stringify(pageConfig)},
250
256
  // @ts-ignore
251
257
  ${shallowStringify(pagesMap)},
@@ -1,9 +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')
5
4
  const parseRequest = require('../utils/parse-request')
6
- const getMainCompilation = require('../utils/get-main-compilation')
5
+
6
+ // const matchCondition = require('../utils/match-condition')
7
7
 
8
8
  function calculateRootEleChild (arr) {
9
9
  if (!arr) {
@@ -21,19 +21,30 @@ function calculateRootEleChild (arr) {
21
21
  }, 0)
22
22
  }
23
23
 
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
24
+ module.exports = function (template, {
25
+ loaderContext,
26
+ // hasScoped,
27
+ hasComment,
28
+ isNative,
29
+ srcMode,
30
+ moduleId,
31
+ ctorType,
32
+ usingComponents,
33
+ componentGenerics
34
+ }, callback) {
35
+ const mpx = loaderContext.getMpx()
36
+ const {
37
+ mode,
38
+ defs,
39
+ wxsContentMap,
40
+ decodeHTMLText,
41
+ externalClasses,
42
+ checkUsingComponents
43
+ // autoVirtualHostRules
44
+ } = mpx
45
+ const { resourcePath } = parseRequest(loaderContext.resource)
32
46
  const builtInComponentsMap = {}
33
- const compilation = loaderContext._compilation
34
- const mainCompilation = getMainCompilation(compilation)
35
- const mpx = mainCompilation.__mpx__
36
- const wxsContentMap = mpx.wxsContentMap
47
+
37
48
  let wxsModuleMap, genericsInfo
38
49
  let output = '/* template */\n'
39
50
 
@@ -43,7 +54,7 @@ module.exports = function (template, options, callback) {
43
54
  content: '<div class="app"><mpx-keep-alive><router-view class="page"></router-view></mpx-keep-alive></div>'
44
55
  }
45
56
  builtInComponentsMap['mpx-keep-alive'] = {
46
- resource: addQuery('@mpxjs/webpack-plugin/lib/runtime/components/web/mpx-keep-alive.vue', { component: true })
57
+ resource: addQuery('@mpxjs/webpack-plugin/lib/runtime/components/web/mpx-keep-alive.vue', { isComponent: true })
47
58
  }
48
59
  }
49
60
 
@@ -62,7 +73,7 @@ module.exports = function (template, options, callback) {
62
73
  }
63
74
  if (template.content) {
64
75
  const templateSrcMode = template.mode || srcMode
65
- const parsed = templateCompiler.parse(template.content, {
76
+ const { root, meta } = templateCompiler.parse(template.content, {
66
77
  warn: (msg) => {
67
78
  loaderContext.emitWarning(
68
79
  new Error('[template compiler][' + loaderContext.resource + ']: ' + msg)
@@ -73,52 +84,59 @@ module.exports = function (template, options, callback) {
73
84
  new Error('[template compiler][' + loaderContext.resource + ']: ' + msg)
74
85
  )
75
86
  },
76
- usingComponents: options.usingComponents,
77
- hasComment: options.hasComment,
78
- isNative: options.isNative,
79
- basename: path.basename(resourcePath),
87
+ usingComponents,
88
+ hasComment,
89
+ isNative,
80
90
  isComponent: ctorType === 'component',
81
91
  mode,
82
92
  srcMode: templateSrcMode,
83
93
  defs,
84
- decodeHTMLText: options.decodeHTMLText,
85
- externalClasses: options.externalClasses,
94
+ decodeHTMLText,
95
+ externalClasses,
96
+ // todo 后续输出web也采用mpx的scoped处理
86
97
  hasScoped: false,
87
98
  moduleId,
88
99
  filePath: loaderContext.resourcePath,
89
100
  i18n: null,
90
- checkUsingComponents: options.checkUsingComponents,
101
+ checkUsingComponents,
91
102
  // web模式下全局组件不会被合入usingComponents中,故globalComponents可以传空
92
103
  globalComponents: [],
93
104
  // web模式下实现抽象组件
94
- componentGenerics: options.componentGenerics
105
+ componentGenerics
106
+ // todo 后续输出web也基于autoVirtualHostRules决定是否添加root wrapper
107
+ // hasVirtualHost: matchCondition(resourcePath, autoVirtualHostRules)
95
108
  })
96
- if (parsed.meta.wxsModuleMap) {
97
- wxsModuleMap = parsed.meta.wxsModuleMap
109
+ if (meta.wxsModuleMap) {
110
+ wxsModuleMap = meta.wxsModuleMap
98
111
  }
99
- if (parsed.meta.wxsContentMap) {
100
- for (let module in parsed.meta.wxsContentMap) {
101
- wxsContentMap[`${resourcePath}~${module}`] = parsed.meta.wxsContentMap[module]
112
+ if (meta.wxsContentMap) {
113
+ for (let module in meta.wxsContentMap) {
114
+ wxsContentMap[`${resourcePath}~${module}`] = meta.wxsContentMap[module]
102
115
  }
103
116
  }
104
- if (parsed.meta.builtInComponentsMap) {
105
- Object.keys(parsed.meta.builtInComponentsMap).forEach((name) => {
117
+ if (meta.builtInComponentsMap) {
118
+ Object.keys(meta.builtInComponentsMap).forEach((name) => {
106
119
  builtInComponentsMap[name] = {
107
- resource: addQuery(parsed.meta.builtInComponentsMap[name], { component: true })
120
+ resource: addQuery(meta.builtInComponentsMap[name], { isComponent: true })
108
121
  }
109
122
  })
110
123
  }
111
- if (parsed.meta.genericsInfo) {
112
- genericsInfo = parsed.meta.genericsInfo
124
+ if (meta.genericsInfo) {
125
+ genericsInfo = meta.genericsInfo
113
126
  }
114
- // 输出H5有多个root element时, 使用div标签包裹
115
- if (parsed.root.tag === 'temp-node') {
116
- const childLen = calculateRootEleChild(parsed.root.children)
127
+ // 输出H5有多个root element时, 使用mpx-root-view标签包裹
128
+ // todo 后续输出web也基于autoVirtualHostRules决定是否添加root wrapper
129
+ if (root.tag === 'temp-node') {
130
+ const childLen = calculateRootEleChild(root.children)
117
131
  if (childLen >= 2) {
118
- parsed.root.tag = 'div'
132
+ root.tag = 'div'
133
+ templateCompiler.addAttrs(root, [{
134
+ name: 'class',
135
+ value: 'mpx-root-view'
136
+ }])
119
137
  }
120
138
  }
121
- return templateCompiler.serialize(parsed.root)
139
+ return templateCompiler.serialize(root)
122
140
  }
123
141
  })
124
142
  output += '\n\n'
@@ -1,12 +1,9 @@
1
- // const htmlMinifier = require('html-minifier')
2
1
  const attrParse = require('./attributesParser')
3
2
  const loaderUtils = require('loader-utils')
4
3
  const url = require('url')
5
4
  const config = require('../config')
6
- const getMainCompilation = require('../utils/get-main-compilation')
7
5
  const createHelpers = require('../helpers')
8
6
  const isUrlRequest = require('../utils/is-url-request')
9
- const addQuery = require('../utils/add-query')
10
7
  const parseRequest = require('../utils/parse-request')
11
8
 
12
9
  function randomIdent () {
@@ -14,13 +11,13 @@ function randomIdent () {
14
11
  }
15
12
 
16
13
  module.exports = function (content) {
17
- const loaderContext = this
18
- const isProduction = this.minimize || process.env.NODE_ENV === 'production'
19
14
  const options = loaderUtils.getOptions(this) || {}
20
- const mpx = getMainCompilation(this._compilation).__mpx__
15
+ const mpx = this.getMpx()
16
+ const root = mpx.projectRoot
17
+ const externals = mpx.externals
21
18
 
22
- const { resourcePath: filePath, queryObj } = parseRequest(this.resource)
23
- const moduleId = 'm' + mpx.pathHash(filePath)
19
+ const { queryObj } = parseRequest(this.resource)
20
+ const moduleId = queryObj.moduleId
24
21
  const hasScoped = false
25
22
  const hasComment = false
26
23
  const isNative = true
@@ -28,25 +25,10 @@ module.exports = function (content) {
28
25
  const usingComponents = []
29
26
 
30
27
  const mode = mpx.mode
31
- const globalSrcMode = mpx.srcMode
32
28
  const localSrcMode = queryObj.mode
33
- const srcMode = localSrcMode || globalSrcMode
34
29
  const customAttributes = options.attributes || mpx.attributes || []
35
30
 
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
- })
31
+ const { getRequestString } = createHelpers(this)
50
32
 
51
33
  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)
52
34
 
@@ -64,7 +46,7 @@ module.exports = function (content) {
64
46
  const data = {}
65
47
  content = [content]
66
48
  links.forEach(function (link) {
67
- if (!isUrlRequest(link.value, options.root)) return
49
+ if (!isUrlRequest(link.value, root, externals)) return
68
50
 
69
51
  if (link.value.indexOf('mailto:') > -1) return
70
52
 
@@ -88,57 +70,39 @@ module.exports = function (content) {
88
70
  })
89
71
  content.reverse()
90
72
  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
-
119
73
  content = JSON.stringify(content)
120
74
 
121
75
  const exportsString = 'module.exports = '
122
76
 
123
- return exportsString + content.replace(/xxxHTMLLINKxxx[0-9.]+xxx/g, function (match) {
77
+ return exportsString + content.replace(/xxxHTMLLINKxxx[0-9.]+xxx/g, (match) => {
124
78
  if (!data[match]) return match
125
79
 
126
80
  const link = data[match]
127
81
 
128
- let src = loaderUtils.urlToRequest(link.value, options.root)
129
- src = addQuery(src, { isStatic: true })
82
+ let src = loaderUtils.urlToRequest(link.value, root)
130
83
 
131
- let requestString
84
+ let requestString, extraOptions
132
85
 
133
86
  switch (link.tag) {
134
87
  case 'import':
135
88
  case 'include':
136
- requestString = getSrcRequestString('template', { src, mode: localSrcMode }, -1)
89
+ extraOptions = {
90
+ hasScoped,
91
+ hasComment,
92
+ isNative,
93
+ moduleId,
94
+ usingComponents,
95
+ isStatic: true
96
+ }
97
+ requestString = getRequestString('template', { src, mode: localSrcMode }, extraOptions)
137
98
  break
138
99
  case config[mode].wxs.tag:
139
100
  // 显式传递issuerResource避免模块缓存以及提供给wxs-loader计算相对路径
140
- src = addQuery(src, { issuerResource: loaderContext.resource })
141
- requestString = getSrcRequestString('wxs', { src, mode: localSrcMode }, -1, undefined, '!!')
101
+ extraOptions = {
102
+ issuerFile: mpx.getExtractedFile(this.resource),
103
+ isStatic: true
104
+ }
105
+ requestString = getRequestString('wxs', { src, mode: localSrcMode }, extraOptions)
142
106
  break
143
107
  default:
144
108
  requestString = JSON.stringify(src)
@@ -0,0 +1,32 @@
1
+ const {
2
+ compareModulesByPreOrderIndexOrIdentifier
3
+ } = require('webpack/lib/util/comparators')
4
+ const { assignAscendingModuleIds } = require('webpack/lib/ids/IdHelpers')
5
+
6
+ /** @typedef {import("../Compiler")} Compiler */
7
+ /** @typedef {import("../Module")} Module */
8
+
9
+ class WxsModuleIdsPlugin {
10
+ apply (compilation) {
11
+ compilation.hooks.moduleIds.tap({
12
+ name: 'WxsModuleIdsPlugin',
13
+ // 放在最前面执行,确保生成的代码模块为数组形式,符合wxs规范
14
+ stage: -1000
15
+ }, modules => {
16
+ const chunkGraph = compilation.chunkGraph
17
+ const modulesInNaturalOrder = Array.from(modules)
18
+ .filter(
19
+ m =>
20
+ m.needId &&
21
+ chunkGraph.getNumberOfModuleChunks(m) > 0 &&
22
+ chunkGraph.getModuleId(m) === null
23
+ )
24
+ .sort(
25
+ compareModulesByPreOrderIndexOrIdentifier(compilation.moduleGraph)
26
+ )
27
+ assignAscendingModuleIds(modulesInNaturalOrder, compilation)
28
+ })
29
+ }
30
+ }
31
+
32
+ module.exports = WxsModuleIdsPlugin
@@ -3,11 +3,11 @@ class WxsParserPlugin {
3
3
  this.options = options
4
4
  }
5
5
 
6
- apply (parser, compilation) {
6
+ apply (parser) {
7
7
  parser.hooks.program.tap({
8
8
  name: 'WxsParserPlugin',
9
9
  // 放在最后面执行
10
- stage: 100
10
+ stage: 1000
11
11
  }, ast => {
12
12
  const module = parser.state.module
13
13
  if (module.buildInfo) {
@@ -1,5 +1,6 @@
1
1
  const WxsTemplatePlugin = require('./WxsTemplatePlugin')
2
2
  const WxsParserPlugin = require('./WxsParserPlugin')
3
+ const WxsModuleIdsPlugin = require('./WxsModuleIdsPlugin')
3
4
 
4
5
  class WxsPlugin {
5
6
  constructor (options = { mode: 'wx' }) {
@@ -8,20 +9,15 @@ class WxsPlugin {
8
9
 
9
10
  apply (compiler) {
10
11
  compiler.hooks.thisCompilation.tap('WxsPlugin', (compilation, { normalModuleFactory }) => {
11
- new WxsTemplatePlugin(this.options).apply(
12
- compilation.mainTemplate,
13
- compilation
14
- )
12
+ new WxsTemplatePlugin(this.options).apply(compilation)
13
+ new WxsModuleIdsPlugin(this.options).apply(compilation)
15
14
 
16
15
  compilation.hooks.buildModule.tap('WxsPlugin', (module) => {
17
16
  module.wxs = true
18
17
  })
19
18
 
20
19
  const handler = (parser) => {
21
- new WxsParserPlugin(this.options).apply(
22
- parser,
23
- compilation
24
- )
20
+ new WxsParserPlugin(this.options).apply(parser)
25
21
  }
26
22
 
27
23
  normalModuleFactory.hooks.parser
@@ -1,104 +1,58 @@
1
- const Template = require('webpack/lib/Template')
2
1
  const config = require('../config')
3
- const { ConcatSource } = require('webpack-sources')
2
+ const { ConcatSource } = require('webpack').sources
3
+ const JavascriptModulesPlugin = require('webpack/lib/javascript/JavascriptModulesPlugin')
4
4
 
5
- module.exports = class WxsMainTemplatePlugin {
5
+ module.exports = class WxsTemplatePlugin {
6
6
  constructor (options = { mode: 'wx' }) {
7
7
  this.options = options
8
8
  }
9
9
 
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
- ])
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
- )
10
+ apply (compilation) {
11
+ const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation)
81
12
 
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)
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)
97
16
  })
98
17
 
99
- mainTemplate.hooks.hash.tap('WxsMainTemplatePlugin', hash => {
100
- hash.update('wxs')
101
- hash.update(this.options.mode)
18
+ hooks.render.tap('WxsTemplatePlugin', (source) => {
19
+ const prefix = config[this.options.mode].wxs.templatePrefix
20
+ return new ConcatSource(prefix, source)
102
21
  })
22
+
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
+ // )
103
57
  }
104
58
  }
@@ -1,10 +1,8 @@
1
1
  // 该loader用于将用户定义的messages注入到i18n.wxs中
2
- const getMainCompilation = require('../utils/get-main-compilation')
3
2
  const loaderUtils = require('loader-utils')
4
3
 
5
4
  module.exports = function (content) {
6
- const mainCompilation = getMainCompilation(this._compilation)
7
- const i18n = mainCompilation.__mpx__.i18n
5
+ const i18n = this.getMpx().i18n
8
6
  let prefix = 'var __mpx_messages__, __mpx_datetime_formats__, __mpx_number_formats__\n'
9
7
  if (i18n) {
10
8
  if (i18n.messages) {