@mpxjs/webpack-plugin 2.10.6-beta.2 → 2.10.6-beta.3

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.
@@ -1,280 +0,0 @@
1
- const templateCompiler = require('../template-compiler/compiler')
2
- const parseRequest = require('../utils/parse-request')
3
- const addQuery = require('../utils/add-query')
4
- const { buildComponentsMap } = require('./script-helper')
5
- const loaderUtils = require('loader-utils')
6
- const normalize = require('../utils/normalize')
7
- const domTagConfig = require('../utils/dom-tag-config')
8
- const optionProcessorPath = normalize.lib('runtime/optionProcessor')
9
- const shallowStringify = require('../utils/shallow-stringify')
10
- const { stringifyRequest } = require('./script-helper')
11
- const parseQuery = require('loader-utils').parseQuery
12
- const wxmlTemplateLoader = normalize.lib('web/wxml-template-loader')
13
-
14
- const getRefVarNames = function (str = '', discardProp) { // 获取元素属性上用到的动态数据keyname
15
- const regex = /\(([a-zA-Z_$]\w*)\)/g
16
- const matches = str.match(regex) || []
17
- const variableNames = []
18
- matches.forEach(name => {
19
- const getName = /\((\w+)\)/.exec(name)
20
- if (!discardProp.includes(getName[1]) && getName[1]) {
21
- variableNames.push(getName[1].trim())
22
- }
23
- })
24
- return variableNames
25
- }
26
-
27
- const getTextVarName = function (str = '', discardProp) { // 获取文本中的动态数据keyname
28
- const regex = /\{\{([^{}]+?)(?:\..*?)?\}\}/g
29
- const variables = []
30
- let match
31
-
32
- while ((match = regex.exec(str)) !== null) {
33
- const inner = match[1] // 匹配 {{...}} 内部内容
34
- const varName = inner.split('.')[0]
35
- if (!discardProp.includes(varName) && varName) {
36
- variables.push(varName.trim())
37
- }
38
- }
39
- return variables
40
- }
41
-
42
- // 所有的props是在遍历模版的时候收集的,需要把true/false/for上面定义的item index剔除掉
43
- const addDiscardProp = function (attrList, discardProp) {
44
- for (let i = 0; i < attrList.length; i++) {
45
- if (attrList[i].name === 'v-for') {
46
- const regex = /\(([^)]+)\)/
47
- const match = attrList[i].value?.match(regex)
48
- if (match) {
49
- const discardValue = match[1].split(',').map(s => s.trim()) || []
50
- discardProp.push(...discardValue)
51
- }
52
- }
53
- }
54
- }
55
-
56
- const getEventName = function (eventStr = '') { // 获取事件用到的动态数据keyname 返回数组是避免将空值写入prop
57
- const match = eventStr.match(/\[\[\s*"([^"]*)"\s*\]\]/)
58
- if (match) {
59
- const extractedValue = match[1]
60
- const trimmedValue = extractedValue
61
- return [trimmedValue]
62
- }
63
- return []
64
- }
65
-
66
- module.exports = function (content) {
67
- const mpx = this.getMpx()
68
- const {
69
- wxsContentMap,
70
- projectRoot
71
- } = mpx
72
- this._compiler = true
73
- const query = parseQuery(this.resourceQuery)
74
- if (!query.is) {
75
- return content
76
- }
77
- let parentLocalComponentsMap = {}
78
- try {
79
- parentLocalComponentsMap = JSON.parse(query.localComponentsMap) // 拿取父组件上面的所有本地组件
80
- } catch (e) {}
81
- const { resourcePath, rawResourcePath } = parseRequest(this.resource)
82
- const props = ['_data_v_id']
83
- const { root, meta } = templateCompiler.parse(content, { // 调用已有的parse方法处理模版
84
- warn: (msg) => {
85
- this.emitWarning(
86
- new Error('[template compiler][' + this.resource + ']: ' + msg)
87
- )
88
- },
89
- error: (msg) => {
90
- this.emitError(
91
- new Error('[template compiler][' + this.resource + ']: ' + msg)
92
- )
93
- },
94
- isTemp2vue: true,
95
- mode: 'web',
96
- srcMode: 'wx',
97
- filePath: resourcePath,
98
- usingComponents: []
99
- })
100
- const builtInComponentsMap = {}
101
- if (meta.builtInComponentsMap) {
102
- Object.keys(meta.builtInComponentsMap).forEach((name) => {
103
- builtInComponentsMap[name] = {
104
- resource: addQuery(meta.builtInComponentsMap[name], { isComponent: true })
105
- }
106
- })
107
- }
108
-
109
- if (meta.wxsContentMap) {
110
- for (const module in meta.wxsContentMap) {
111
- wxsContentMap[`${rawResourcePath}~${module}`] = meta.wxsContentMap[module]
112
- }
113
- }
114
- const eventReg = /^@[a-zA-Z]+/
115
- let isFindRoot = false
116
- const componentNames = [] // 记录引用多少个组件
117
- const localComponentsTags = []
118
- function serialize (root) {
119
- function walk (node, discardProp) {
120
- let result = ''
121
- if (node) {
122
- if (node.type === 3) {
123
- if (node.isComment) {
124
- result += '<!--' + node.text + '-->'
125
- } else {
126
- const text = getTextVarName(node.text, discardProp) || []
127
- props.push(...text)
128
- result += node.text
129
- }
130
- }
131
- if (node.type === 1) {
132
- if (node.tag === 'wxs' || node.tag === 'import') { // wxml文件里不支持import wxs后续支持
133
- return ''
134
- } else if (node.tag !== 'temp-node') {
135
- if (node.tag === 'component') { // 提前处理component上的bind逻辑,确保传入_data_v_id
136
- if (!node.attrsMap['v-bind']) {
137
- node.attrsList.push({
138
- name: 'v-bind',
139
- value: '{_data_v_id}'
140
- })
141
- } else {
142
- node.attrsList.forEach(function (attr) {
143
- if (attr.name === 'v-bind') {
144
- attr.value = attr.value.replace('}', ', _data_v_id}')
145
- }
146
- })
147
- }
148
- }
149
- if (node.tag === 'template' && !node._fakeTemplate) {
150
- if (node.attrsMap.name) { // template name处理逻辑
151
- if (isFindRoot) {
152
- componentNames.push(node.attrsMap.name)
153
- return ''
154
- }
155
- isFindRoot = true
156
- result += '<' + node.tag
157
- } else { // 其他template逻辑全部丢弃
158
- return ''
159
- }
160
- } else {
161
- const { isBuildInTag, isOriginTag } = domTagConfig
162
- if (!isBuildInTag(node.tag) && !isOriginTag(node.tag)) {
163
- localComponentsTags.push(node.tag)
164
- }
165
- result += '<' + node.tag
166
- const tagProps = []
167
- addDiscardProp(node.attrsList, discardProp)
168
- node.attrsList.forEach(function (attr) {
169
- if (attr.name === ':class') {
170
- if (attr.value.trim().startsWith('[') && attr.value.trim().endsWith(']')) { // 数组情况下_data_v_id直接插在最后面
171
- attr.value = attr.value.replace(']', ', _data_v_id]')
172
- } else if (attr.value) {
173
- attr.value = `[${attr.value}, _data_v_id]` // 非数组情况下包装成数组后_data_v_id直接插在最后面
174
- }
175
- }
176
- const value = attr.value
177
- if (eventReg.exec(attr.name)) { // 事件
178
- const result = getEventName(attr.value)
179
- tagProps.push(...result)
180
- } else { // 属性
181
- const result = getRefVarNames(value, discardProp)
182
- tagProps.push(...result)
183
- }
184
- result += ' ' + attr.name
185
- if (value != null) {
186
- result += '=' + templateCompiler.stringifyAttr(value)
187
- }
188
- })
189
- props.push(...tagProps)
190
- }
191
- if (node.unary) {
192
- result += '/>'
193
- } else {
194
- result += '>'
195
- node.children.forEach(function (child) {
196
- result += walk(child, discardProp)
197
- })
198
- result += '</' + node.tag + '>'
199
- }
200
- } else {
201
- node.children.forEach(function (child) {
202
- result += walk(child, discardProp)
203
- })
204
- }
205
- }
206
- }
207
- discardProp.splice(2) // 清理掉本次循环记录的数据避免污染其他同级的props判断
208
- return result
209
- }
210
- return walk(root, ['true', 'false'])
211
- }
212
- const tempCompMaps = []
213
- const path = this.resourcePath || ''
214
- const template = serialize(root)
215
- componentNames.forEach((item) => {
216
- tempCompMaps[item] = {
217
- resource: `${path.replace(query.is, item)}?is=${item}&isTemplate`
218
- }
219
- })
220
-
221
- const localComponentsMap = {}
222
- localComponentsTags.forEach((item) => { // 做一次过滤避免不必要的自定义组件加载
223
- if (parentLocalComponentsMap[item]) {
224
- localComponentsMap[item] = parentLocalComponentsMap[item]
225
- }
226
- })
227
- const componentsMap = buildComponentsMap({ localComponentsMap, builtInComponentsMap, loaderContext: this, jsonConfig: {} })
228
- let script = `\n<script>\n
229
- import proxyEventMixin from '@mpxjs/core/src/platform/builtInMixins/proxyEventMixin.web.js'
230
- import MpxProxy from '@mpxjs/core/src/core/proxy.js'
231
- const {getComponent} = require(${stringifyRequest(this, optionProcessorPath)})\n`
232
- script += 'const templateModules = {}\n'
233
- meta.templateSrcList?.forEach((item) => {
234
- script += `
235
- const tempLoaderResult = require(${stringifyRequest(this, `!!${wxmlTemplateLoader}!${item}`)})\n
236
- Object.assign(templateModules, tempLoaderResult)\n`
237
- })
238
-
239
- // 注入wxs模块
240
- const wxsModuleMap = meta.wxsModuleMap
241
- script += ' var wxsModules = {}\n'
242
- const finalProp = [...(new Set(props))]
243
- if (wxsModuleMap) {
244
- Object.keys(wxsModuleMap).forEach((module) => {
245
- const src = loaderUtils.urlToRequest(wxsModuleMap[module], projectRoot)
246
- const expression = `require(${stringifyRequest(this, src)})`
247
- const index = finalProp.indexOf(module)
248
- if (index > -1) { // 干掉模版中收集的wxs的字段
249
- finalProp.splice(index, 1)
250
- }
251
- script += ` wxsModules.${module} = ${expression}\n`
252
- })
253
- }
254
- script += `export default {
255
- name: '${query.is}',
256
- props: ${JSON.stringify(finalProp)},
257
- mixins: [proxyEventMixin()],
258
- beforeCreate () {
259
- this.__mpxProxy = new MpxProxy({}, this, true)
260
- this.__mpxProxy.created()
261
- Object.keys(wxsModules).forEach((key) => {
262
- if (key in this) {
263
- console.error('[Mpx runtime error]: The wxs module key ['+key+'}] exist in the component/page instance already, please check and rename it!')
264
- } else {
265
- this[key] = wxsModules[key]
266
- }
267
- })
268
- },
269
- components: Object.assign(${shallowStringify(componentsMap)}, templateModules),
270
- }
271
- </script>`
272
- const text = template + script
273
- if (query.type === 'template') {
274
- return template
275
- } else if (query.type === 'script') {
276
- return script
277
- } else {
278
- return text
279
- }
280
- }
@@ -1,29 +0,0 @@
1
- const normalize = require('@mpxjs/webpack-plugin/lib/utils/normalize')
2
- const optionProcessorPath = normalize.lib('runtime/optionProcessor')
3
- const shallowStringify = require('../utils/shallow-stringify')
4
- const getTemplateContent = require('../utils/get-template-content')
5
- const { stringifyRequest } = require('@mpxjs/webpack-plugin/lib/web/script-helper')
6
- const WriteVfsDependency = require('../dependencies/WriteVfsDependency')
7
-
8
- module.exports = function (content) {
9
- const regex = /<template[^>]*\sname\s*=\s*"([^"]*)"[^>]*>/g
10
- const mpx = this.getMpx()
11
- let match
12
- const templateNames = []
13
-
14
- while ((match = regex.exec(content)) !== null) {
15
- templateNames.push(match[1])
16
- }
17
- const templateMaps = {}
18
- templateNames.forEach((name, index) => {
19
- const cutContent = getTemplateContent(content, name)
20
- const resourcePath = this.resourcePath.replace(/.wxml$/, `-${name}.wxml`)
21
- this._module.addPresentationalDependency(new WriteVfsDependency(resourcePath, cutContent))
22
- mpx.__vfs.writeModule(resourcePath, cutContent)
23
- templateMaps[name] = `getComponent(require(${stringifyRequest(this, `${resourcePath}?is=${name}&localComponentsMap=${encodeURIComponent(JSON.stringify(mpx.parentLocalComponentsMap))}&isTemplate`)}))` // template2vue是在外部配置没办法拿到parentLocalComponentsMap,所以通过query传递
24
- })
25
- return `
26
- const {getComponent} = require(${stringifyRequest(this, optionProcessorPath)})\n
27
- module.exports = ${shallowStringify(templateMaps)}
28
- `
29
- }