@mpxjs/webpack-plugin 2.6.115 → 2.7.0-alpha

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/LICENSE +433 -0
  2. package/README.md +1 -1
  3. package/lib/config.js +14 -0
  4. package/lib/dependencies/AddEntryDependency.js +24 -0
  5. package/lib/dependencies/AppEntryDependency.js +58 -0
  6. package/lib/dependencies/CommonJsAsyncDependency.js +51 -0
  7. package/lib/dependencies/CommonJsVariableDependency.js +81 -0
  8. package/lib/dependencies/DynamicEntryDependency.js +171 -0
  9. package/lib/dependencies/FlagPluginDependency.js +24 -0
  10. package/lib/dependencies/InjectDependency.js +43 -0
  11. package/lib/dependencies/RecordGlobalComponentsDependency.js +50 -0
  12. package/lib/dependencies/RecordIndependentDependency.js +44 -0
  13. package/lib/dependencies/RecordResourceMapDependency.js +62 -0
  14. package/lib/dependencies/RemoveEntryDependency.js +40 -0
  15. package/lib/{dependency → dependencies}/ReplaceDependency.js +19 -2
  16. package/lib/dependencies/ResolveDependency.js +88 -0
  17. package/lib/extractor.js +82 -178
  18. package/lib/file-loader.js +7 -19
  19. package/lib/helpers.js +39 -334
  20. package/lib/independent-loader.js +52 -0
  21. package/lib/index.js +889 -525
  22. package/lib/json-compiler/helper.js +156 -0
  23. package/lib/json-compiler/index.js +245 -451
  24. package/lib/json-compiler/plugin.js +150 -0
  25. package/lib/json-compiler/{theme-loader.js → theme.js} +5 -3
  26. package/lib/loader.js +178 -241
  27. package/lib/native-loader.js +71 -133
  28. package/lib/parser.js +1 -2
  29. package/lib/partial-compile/index.js +35 -0
  30. package/lib/platform/json/wx/index.js +1 -1
  31. package/lib/platform/template/normalize-component-rules.js +2 -3
  32. package/lib/platform/template/wx/component-config/button.js +14 -2
  33. package/lib/platform/template/wx/component-config/image.js +4 -0
  34. package/lib/platform/template/wx/component-config/input.js +4 -0
  35. package/lib/platform/template/wx/component-config/rich-text.js +4 -0
  36. package/lib/platform/template/wx/component-config/scroll-view.js +4 -0
  37. package/lib/platform/template/wx/component-config/switch.js +4 -0
  38. package/lib/platform/template/wx/component-config/text.js +4 -0
  39. package/lib/platform/template/wx/component-config/textarea.js +5 -0
  40. package/lib/platform/template/wx/component-config/view.js +4 -0
  41. package/lib/platform/template/wx/index.js +149 -3
  42. package/lib/record-loader.js +11 -0
  43. package/lib/resolve-loader.js +6 -0
  44. package/lib/resolver/AddEnvPlugin.js +4 -3
  45. package/lib/resolver/AddModePlugin.js +4 -3
  46. package/lib/resolver/FixDescriptionInfoPlugin.js +28 -0
  47. package/lib/resolver/PackageEntryPlugin.js +23 -36
  48. package/lib/runtime/base.styl +5 -0
  49. package/lib/runtime/components/tenon/getInnerListeners.js +317 -0
  50. package/lib/runtime/components/tenon/tenon-button.vue +305 -0
  51. package/lib/runtime/components/tenon/tenon-image.vue +61 -0
  52. package/lib/runtime/components/tenon/tenon-input.vue +99 -0
  53. package/lib/runtime/components/tenon/tenon-rich-text.vue +21 -0
  54. package/lib/runtime/components/tenon/tenon-scroll-view.vue +124 -0
  55. package/lib/runtime/components/tenon/tenon-switch.vue +91 -0
  56. package/lib/runtime/components/tenon/tenon-text-area.vue +64 -0
  57. package/lib/runtime/components/tenon/tenon-text.vue +64 -0
  58. package/lib/runtime/components/tenon/tenon-view.vue +93 -0
  59. package/lib/runtime/components/tenon/util.js +44 -0
  60. package/lib/runtime/components/web/getInnerListeners.js +1 -3
  61. package/lib/runtime/components/web/mpx-image.vue +20 -5
  62. package/lib/runtime/components/web/mpx-movable-view.vue +6 -2
  63. package/lib/runtime/components/web/mpx-swiper.vue +18 -3
  64. package/lib/runtime/i18n.wxs +31 -11
  65. package/lib/runtime/optionProcessor.js +48 -3
  66. package/lib/runtime/optionProcessor.tenon.js +386 -0
  67. package/lib/selector.js +29 -10
  68. package/lib/style-compiler/index.js +16 -24
  69. package/lib/style-compiler/load-postcss-config.js +3 -1
  70. package/lib/style-compiler/plugins/conditional-strip.js +68 -65
  71. package/lib/style-compiler/plugins/hm.js +20 -0
  72. package/lib/style-compiler/plugins/rpx.js +43 -37
  73. package/lib/style-compiler/plugins/scope-id.js +79 -72
  74. package/lib/style-compiler/plugins/trans-special.js +25 -18
  75. package/lib/style-compiler/plugins/trim.js +13 -7
  76. package/lib/style-compiler/plugins/vw.js +22 -16
  77. package/lib/template-compiler/compiler.js +106 -199
  78. package/lib/template-compiler/index.js +52 -139
  79. package/lib/template-compiler/trans-dynamic-class-expr.js +18 -13
  80. package/lib/tenon/index.js +105 -0
  81. package/lib/tenon/processJSON.js +356 -0
  82. package/lib/tenon/processScript.js +261 -0
  83. package/lib/tenon/processStyles.js +21 -0
  84. package/lib/tenon/processTemplate.js +133 -0
  85. package/lib/url-loader.js +11 -29
  86. package/lib/utils/add-query.js +1 -1
  87. package/lib/utils/const.js +10 -0
  88. package/lib/utils/emit-file.js +10 -0
  89. package/lib/utils/eval-json-js.js +31 -0
  90. package/lib/utils/get-entry-name.js +13 -0
  91. package/lib/utils/get-json-content.js +42 -0
  92. package/lib/utils/get-relative-path.js +25 -0
  93. package/lib/utils/is-url-request.js +10 -1
  94. package/lib/utils/match-condition.js +4 -1
  95. package/lib/utils/normalize.js +4 -15
  96. package/lib/utils/parse-request.js +3 -3
  97. package/lib/utils/resolve.js +13 -0
  98. package/lib/utils/set.js +47 -0
  99. package/lib/utils/stringify-loaders-resource.js +25 -0
  100. package/lib/utils/stringify-query.js +4 -0
  101. package/lib/web/processJSON.js +113 -144
  102. package/lib/web/processScript.js +47 -34
  103. package/lib/web/processTemplate.js +57 -40
  104. package/lib/wxml/{wxml-loader.js → loader.js} +21 -62
  105. package/lib/wxs/WxsModuleIdsPlugin.js +29 -0
  106. package/lib/wxs/WxsParserPlugin.js +2 -2
  107. package/lib/wxs/WxsPlugin.js +4 -8
  108. package/lib/wxs/WxsTemplatePlugin.js +46 -92
  109. package/lib/wxs/{wxs-i18n-loader.js → i18n-loader.js} +5 -4
  110. package/lib/wxs/loader.js +142 -0
  111. package/lib/wxs/{wxs-pre-loader.js → pre-loader.js} +20 -5
  112. package/lib/wxss/loader.js +31 -43
  113. package/lib/wxss/localsLoader.js +1 -5
  114. package/lib/wxss/processCss.js +107 -103
  115. package/package.json +21 -18
  116. package/lib/built-in-loader.js +0 -49
  117. package/lib/content-loader.js +0 -13
  118. package/lib/dependency/ChildCompileDependency.js +0 -24
  119. package/lib/dependency/InjectDependency.js +0 -26
  120. package/lib/dependency/RemovedModuleDependency.js +0 -23
  121. package/lib/dependency/ResolveDependency.js +0 -49
  122. package/lib/path-loader.js +0 -3
  123. package/lib/plugin-loader.js +0 -287
  124. package/lib/staticConfig.js +0 -4
  125. package/lib/utils/get-main-compilation.js +0 -6
  126. package/lib/utils/read-json-for-src.js +0 -34
  127. package/lib/utils/try-require.js +0 -16
  128. package/lib/wxs/wxs-loader.js +0 -117
  129. package/lib/wxss/getImportPrefix.js +0 -30
@@ -1,9 +1,8 @@
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
+ // const { matchCondition } = require('../utils/match-condition')
7
6
 
8
7
  function calculateRootEleChild (arr) {
9
8
  if (!arr) {
@@ -21,19 +20,30 @@ function calculateRootEleChild (arr) {
21
20
  }, 0)
22
21
  }
23
22
 
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
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)
32
45
  const builtInComponentsMap = {}
33
- const compilation = loaderContext._compilation
34
- const mainCompilation = getMainCompilation(compilation)
35
- const mpx = mainCompilation.__mpx__
36
- const wxsContentMap = mpx.wxsContentMap
46
+
37
47
  let wxsModuleMap, genericsInfo
38
48
  let output = '/* template */\n'
39
49
 
@@ -43,7 +53,7 @@ module.exports = function (template, options, callback) {
43
53
  content: '<div class="app"><mpx-keep-alive><router-view class="page"></router-view></mpx-keep-alive></div>'
44
54
  }
45
55
  builtInComponentsMap['mpx-keep-alive'] = {
46
- resource: addQuery('@mpxjs/webpack-plugin/lib/runtime/components/web/mpx-keep-alive.vue', { component: true })
56
+ resource: addQuery('@mpxjs/webpack-plugin/lib/runtime/components/web/mpx-keep-alive.vue', { isComponent: true })
47
57
  }
48
58
  }
49
59
 
@@ -62,7 +72,7 @@ module.exports = function (template, options, callback) {
62
72
  }
63
73
  if (template.content) {
64
74
  const templateSrcMode = template.mode || srcMode
65
- const parsed = templateCompiler.parse(template.content, {
75
+ const { root, meta } = templateCompiler.parse(template.content, {
66
76
  warn: (msg) => {
67
77
  loaderContext.emitWarning(
68
78
  new Error('[template compiler][' + loaderContext.resource + ']: ' + msg)
@@ -73,52 +83,59 @@ module.exports = function (template, options, callback) {
73
83
  new Error('[template compiler][' + loaderContext.resource + ']: ' + msg)
74
84
  )
75
85
  },
76
- usingComponents: options.usingComponents,
77
- hasComment: options.hasComment,
78
- isNative: options.isNative,
79
- basename: path.basename(resourcePath),
86
+ usingComponents,
87
+ hasComment,
88
+ isNative,
80
89
  isComponent: ctorType === 'component',
81
90
  mode,
82
91
  srcMode: templateSrcMode,
83
92
  defs,
84
- decodeHTMLText: options.decodeHTMLText,
85
- externalClasses: options.externalClasses,
93
+ decodeHTMLText,
94
+ externalClasses,
95
+ // todo 后续输出web也采用mpx的scoped处理
86
96
  hasScoped: false,
87
97
  moduleId,
88
- filePath: loaderContext.resourcePath,
98
+ filePath: resourcePath,
89
99
  i18n: null,
90
- checkUsingComponents: options.checkUsingComponents,
100
+ checkUsingComponents,
91
101
  // web模式下全局组件不会被合入usingComponents中,故globalComponents可以传空
92
102
  globalComponents: [],
93
103
  // web模式下实现抽象组件
94
- componentGenerics: options.componentGenerics
104
+ componentGenerics
105
+ // todo 后续输出web也基于autoVirtualHostRules决定是否添加root wrapper
106
+ // hasVirtualHost: matchCondition(resourcePath, autoVirtualHostRules)
95
107
  })
96
- if (parsed.meta.wxsModuleMap) {
97
- wxsModuleMap = parsed.meta.wxsModuleMap
108
+ if (meta.wxsModuleMap) {
109
+ wxsModuleMap = meta.wxsModuleMap
98
110
  }
99
- if (parsed.meta.wxsContentMap) {
100
- for (let module in parsed.meta.wxsContentMap) {
101
- wxsContentMap[`${resourcePath}~${module}`] = parsed.meta.wxsContentMap[module]
111
+ if (meta.wxsContentMap) {
112
+ for (let module in meta.wxsContentMap) {
113
+ wxsContentMap[`${resourcePath}~${module}`] = meta.wxsContentMap[module]
102
114
  }
103
115
  }
104
- if (parsed.meta.builtInComponentsMap) {
105
- Object.keys(parsed.meta.builtInComponentsMap).forEach((name) => {
116
+ if (meta.builtInComponentsMap) {
117
+ Object.keys(meta.builtInComponentsMap).forEach((name) => {
106
118
  builtInComponentsMap[name] = {
107
- resource: addQuery(parsed.meta.builtInComponentsMap[name], { component: true })
119
+ resource: addQuery(meta.builtInComponentsMap[name], { isComponent: true })
108
120
  }
109
121
  })
110
122
  }
111
- if (parsed.meta.genericsInfo) {
112
- genericsInfo = parsed.meta.genericsInfo
123
+ if (meta.genericsInfo) {
124
+ genericsInfo = meta.genericsInfo
113
125
  }
114
- // 输出H5有多个root element时, 使用div标签包裹
115
- if (parsed.root.tag === 'temp-node') {
116
- const childLen = calculateRootEleChild(parsed.root.children)
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)
117
130
  if (childLen >= 2) {
118
- parsed.root.tag = 'div'
131
+ root.tag = 'div'
132
+ templateCompiler.addAttrs(root, [{
133
+ name: 'class',
134
+ value: 'mpx-root-view'
135
+ }])
119
136
  }
120
137
  }
121
- return templateCompiler.serialize(parsed.root)
138
+ return templateCompiler.serialize(root)
122
139
  }
123
140
  })
124
141
  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,39 +11,21 @@ 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)
24
20
  const hasScoped = false
25
21
  const hasComment = false
26
22
  const isNative = true
27
23
 
28
- const usingComponents = []
29
-
30
24
  const mode = mpx.mode
31
- const globalSrcMode = mpx.srcMode
32
25
  const localSrcMode = queryObj.mode
33
- const srcMode = localSrcMode || globalSrcMode
34
26
  const customAttributes = options.attributes || mpx.attributes || []
35
27
 
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
- })
28
+ const { getRequestString } = createHelpers(this)
50
29
 
51
30
  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
31
 
@@ -64,7 +43,7 @@ module.exports = function (content) {
64
43
  const data = {}
65
44
  content = [content]
66
45
  links.forEach(function (link) {
67
- if (!isUrlRequest(link.value, options.root)) return
46
+ if (!isUrlRequest(link.value, root, externals)) return
68
47
 
69
48
  if (link.value.indexOf('mailto:') > -1) return
70
49
 
@@ -88,57 +67,37 @@ module.exports = function (content) {
88
67
  })
89
68
  content.reverse()
90
69
  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
70
  content = JSON.stringify(content)
120
71
 
121
72
  const exportsString = 'module.exports = '
122
73
 
123
- return exportsString + content.replace(/xxxHTMLLINKxxx[0-9.]+xxx/g, function (match) {
74
+ return exportsString + content.replace(/xxxHTMLLINKxxx[0-9.]+xxx/g, (match) => {
124
75
  if (!data[match]) return match
125
76
 
126
77
  const link = data[match]
127
78
 
128
- let src = loaderUtils.urlToRequest(link.value, options.root)
129
- src = addQuery(src, { isStatic: true })
79
+ let src = loaderUtils.urlToRequest(link.value, root)
130
80
 
131
- let requestString
81
+ let requestString, extraOptions
132
82
 
133
83
  switch (link.tag) {
134
84
  case 'import':
135
85
  case 'include':
136
- requestString = getSrcRequestString('template', { src, mode: localSrcMode }, -1)
86
+ extraOptions = {
87
+ hasScoped,
88
+ hasComment,
89
+ isNative,
90
+ isStatic: true
91
+ }
92
+ requestString = getRequestString('template', { src, mode: localSrcMode }, extraOptions)
137
93
  break
138
94
  case config[mode].wxs.tag:
139
95
  // 显式传递issuerResource避免模块缓存以及提供给wxs-loader计算相对路径
140
- src = addQuery(src, { issuerResource: loaderContext.resource })
141
- requestString = getSrcRequestString('wxs', { src, mode: localSrcMode }, -1, undefined, '!!')
96
+ extraOptions = {
97
+ issuerResource: this.resource,
98
+ isStatic: true
99
+ }
100
+ requestString = getRequestString('wxs', { src, mode: localSrcMode }, extraOptions)
142
101
  break
143
102
  default:
144
103
  requestString = JSON.stringify(src)
@@ -0,0 +1,29 @@
1
+ const {
2
+ compareModulesByPreOrderIndexOrIdentifier
3
+ } = require('webpack/lib/util/comparators')
4
+ const {
5
+ assignAscendingModuleIds,
6
+ getUsedModuleIdsAndModules
7
+ } = require('webpack/lib/ids/IdHelpers')
8
+
9
+ /** @typedef {import("../Compiler")} Compiler */
10
+ /** @typedef {import("../Module")} Module */
11
+
12
+ class WxsModuleIdsPlugin {
13
+ apply (compilation) {
14
+ compilation.hooks.moduleIds.tap({
15
+ name: 'WxsModuleIdsPlugin',
16
+ // 放在最前面执行,确保生成的代码模块为数组形式,符合wxs规范
17
+ stage: -1000
18
+ }, () => {
19
+ const [usedIds, modulesInNaturalOrder] =
20
+ getUsedModuleIdsAndModules(compilation)
21
+ modulesInNaturalOrder.sort(
22
+ compareModulesByPreOrderIndexOrIdentifier(compilation.moduleGraph)
23
+ )
24
+ assignAscendingModuleIds(usedIds, modulesInNaturalOrder, compilation)
25
+ })
26
+ }
27
+ }
28
+
29
+ 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,11 +1,9 @@
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
8
- let prefix = 'var __mpx_messages__, __mpx_datetime_formats__, __mpx_number_formats__\n'
5
+ const i18n = this.getMpx().i18n
6
+ let prefix = 'var __mpx_messages__, __mpx_datetime_formats__, __mpx_number_formats__, __mpx_locale__\n'
9
7
  if (i18n) {
10
8
  if (i18n.messages) {
11
9
  prefix += `__mpx_messages__ = ${JSON.stringify(i18n.messages)}\n`
@@ -22,6 +20,9 @@ module.exports = function (content) {
22
20
  } else if (i18n.numberFormatsPath) {
23
21
  prefix += `__mpx_number_formats__ = require(${loaderUtils.stringifyRequest(this, i18n.numberFormatsPath)})\n`
24
22
  }
23
+ if (i18n.locale) {
24
+ prefix += `__mpx_locale__ = ${JSON.stringify(i18n.locale)}\n`
25
+ }
25
26
  }
26
27
  content = prefix + content
27
28
  return content