-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathindex.js
336 lines (304 loc) · 11.9 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// for mp
const compiler = require('mpvue-template-compiler')
const babel = require('babel-core')
const path = require('path')
const fs = require('fs')
const deepEqual = require('deep-equal')
const { parseConfig, parseComponentsDeps, parseGlobalComponents, clearGlobalComponents, parseMixinsDeps } = require('./parse')
const { parseComponentsDeps: parseComponentsDepsTs } = require('./parse-ts')
const { genPageWxml } = require('./templates')
const { extractScriptFilters, combineScriptAndMixinsFilters } = require('../script-compiler')
const {
cacheFileInfo,
getFileInfo,
getCompNameAndSrc,
getFiltersOutputSrc,
resolveTarget,
covertCCVar,
cacheSlots,
getSlots,
htmlBeautify,
getBabelrc
} = require('./util')
let slotsHookAdded = false
// 调用 compiler 生成 wxml
function genComponentWxml (compiled, options, emitFile, emitError, emitWarning) {
options.components['slots'] = { src: '/components/slots', name: 'slots' }
const { code: wxmlCodeStr, compiled: cp, slots, importCode } = compiler.compileToWxml(compiled, options)
const { mpErrors, mpTips } = cp
// 缓存 slots,延迟编译
cacheSlots(slots, importCode)
if (mpErrors && mpErrors.length) {
emitError(
`\n Error compiling template:\n` +
mpErrors.map(e => ` - ${e}`).join('\n') + '\n'
)
}
if (mpTips && mpTips.length) {
emitWarning(
mpTips.map(e => ` - ${e}`).join('\n') + '\n'
)
}
return htmlBeautify(wxmlCodeStr)
}
function createAppWxml (emitFile, resourcePath, rootComponent, context) {
const { src } = getFileInfo(resourcePath) || {}
const { name: componentName, filePath: wxmlSrc } = getCompNameAndSrc(context, rootComponent)
const wxmlContent = genPageWxml(componentName, wxmlSrc)
emitFile(`${src}.wxml`, wxmlContent)
}
// 更新全局组件时,需要重新生成wxml,用这个字段保存所有需要更新的页面及其参数
const cacheCreateWxmlFns = {}
function createWxml ({ emitWarning, emitError, emitFile, resourcePath, context, compiled }) {
cacheCreateWxmlFns[resourcePath] = arguments
const { pageType, moduleId, components, filters } = getFileInfo(resourcePath) || {}
// TODO, 这儿传 options 进去
// {
// components: {
// 'com-a': { src: '../../components/comA$hash', name: 'comA$hash' }
// },
// pageType: 'component',
// name: 'comA$hash',
// moduleId: 'moduleId'
// }
const { name, filePath: wxmlSrc } = getCompNameAndSrc(context, resourcePath)
const options = { components, pageType, name, moduleId, filters }
const wxmlContent = genComponentWxml(compiled, options, emitFile, emitError, emitWarning)
emitFile(wxmlSrc, wxmlContent)
}
// 编译出 wxml
function compileWxml (compiled, html) {
if (!slotsHookAdded) {
// avoid add hook several times during compilation
slotsHookAdded = true
// TODO: support webpack4
this._compilation.plugin('seal', () => {
const content = getSlots()
if (content.trim()) {
this.emitFile('components/slots.wxml', htmlBeautify(content))
}
// reset flag after slots file emited
slotsHookAdded = false
})
}
return new Promise(resolve => {
const pollComponentsStatus = () => {
const { pageType, components, filters } = getFileInfo(this.resourcePath) || {}
if (!pageType || (components && !components.isCompleted) || (filters && !filters.isCompleted)) {
setTimeout(pollComponentsStatus, 20)
} else {
resolve()
}
}
pollComponentsStatus()
})
.then(() => {
createWxml({
emitWarning: this.emitWarning,
emitError: this.emitError,
emitFile: this.emitFile,
resourcePath: this.resourcePath,
context: this.options.context,
rootComponent: null,
compiled, html
})
})
}
// 针对 .vue 单文件的脚本逻辑的处理
// 处理出当前单文件组件的子组件依赖
function compileMPScript (script, mpOptioins, moduleId) {
const { resourcePath, options, resolve, context, emitFile } = this
const babelrc = getBabelrc(mpOptioins.globalBabelrc)
let result, metadata
let scriptContent = script.content
const babelOptions = { extends: babelrc, plugins: [parseComponentsDeps, parseMixinsDeps] }
if (script.src) { // 处理src
const scriptpath = path.join(path.dirname(resourcePath), script.src)
scriptContent = fs.readFileSync(scriptpath).toString()
}
if (script.lang === 'ts') { // 处理ts
metadata = parseComponentsDepsTs(scriptContent)
} else {
result = babel.transform(scriptContent, babelOptions)
metadata = result.metadata
}
// metadata: importsMap, components
const { importsMap, components: originComponents, mixins } = metadata
const fileInfo = resolveTarget(resourcePath, options.entry)
// 处理子组件的信息
const components = {}
if (originComponents) {
resolveSrc(originComponents, components, resolve, context, options.context).then(() => {
resolveComponent(resourcePath, fileInfo, importsMap, components, moduleId)
}).catch(err => {
console.error(err)
resolveComponent(resourcePath, fileInfo, importsMap, components, moduleId)
})
} else {
resolveComponent(resourcePath, fileInfo, importsMap, components, moduleId)
}
// 处理filters信息
const mixinsFilters = []
if (mixins) {
// 包含外部mixins引用
resolveMixinsFilters(mixins, mixinsFilters, resolve, context, options.context, babelOptions, emitFile).then(() => {
resolveFilters(resourcePath, fileInfo, scriptContent, babelOptions, mixinsFilters, context, options.context, emitFile)
}).catch(err => {
console.error(err)
resolveFilters(resourcePath, fileInfo, scriptContent, babelOptions, mixinsFilters, context, options.context, emitFile)
})
} else {
// 不包外部mixins引用,则直接获取脚本中的filters信息
resolveFilters(resourcePath, fileInfo, scriptContent, babelOptions, mixinsFilters, context, options.context, emitFile)
}
return script
}
// checkMPEntry 针对 entry main.js 的入口处理
// 编译出 app, page 的入口js/wxml/json
let globalComponents
function compileMP (content, mpOptioins) {
const { resourcePath, emitFile, resolve, context, options } = this
const fileInfo = resolveTarget(resourcePath, options.entry)
cacheFileInfo(resourcePath, fileInfo)
const { isApp, isPage } = fileInfo
if (isApp) {
// 解析前将可能存在的全局组件清空
clearGlobalComponents()
}
const babelrc = getBabelrc(mpOptioins.globalBabelrc)
// app入口进行全局component解析
const { metadata } = babel.transform(content, { extends: babelrc, plugins: isApp ? [parseConfig, parseGlobalComponents] : [parseConfig] })
// metadata: config
const { rootComponent, globalComponents: globalComps } = metadata
if (isApp) {
// 保存旧数据,用于对比
const oldGlobalComponents = globalComponents
// 开始解析组件路径时把全局组件清空,解析完成后再进行赋值,标志全局组件解析完成
globalComponents = null
// 解析全局组件的路径
const components = {}
resolveSrc(globalComps, components, resolve, context, options.context).then(() => {
handleResult(components)
}).catch(err => {
console.error(err)
handleResult(components)
})
const handleResult = components => {
globalComponents = components
// 热更时,如果全局组件更新,需要重新生成所有的wxml
if (oldGlobalComponents && !deepEqual(oldGlobalComponents, globalComponents)) {
// 更新所有页面的组件
Object.keys(cacheResolveComponents).forEach(k => {
resolveComponent(...cacheResolveComponents[k])
})
// 重新生成所有wxml
Object.keys(cacheCreateWxmlFns).forEach(k => {
createWxml(...cacheCreateWxmlFns[k])
})
}
}
}
if (isApp || isPage) {
// 这儿应该异步在所有的模块都清晰后再生成
// 生成入口 wxml
if (isPage && rootComponent) {
resolve(context, rootComponent, (err, rootComponentSrc) => {
if (err) return
// 这儿需要搞定 根组件的 路径
createAppWxml(emitFile, resourcePath, rootComponentSrc, this.options.context)
})
}
}
return content
}
function resolveSrc (originComponents, components, resolveFn, context, projectRoot) {
return Promise.all(Object.keys(originComponents).map(k => {
return new Promise((resolve, reject) => {
resolveFn(context, originComponents[k], (err, realSrc) => {
if (err) return reject(err)
const com = covertCCVar(k)
const { filePath, name } = getCompNameAndSrc(projectRoot, realSrc)
components[com] = { src: filePath, name }
resolve()
})
})
}))
}
const cacheResolveComponents = {}
function resolveComponent (resourcePath, fileInfo, importsMap, localComponents, moduleId) {
// 需要等待全局组件解析完成
if (!globalComponents) {
setTimeout(resolveComponent, 20, ...arguments)
} else {
// 保存当前所有参数,在热更时如果全局组件发生变化,需要进行组件更新
cacheResolveComponents[resourcePath] = arguments
const components = Object.assign({}, globalComponents, localComponents)
components.isCompleted = true
cacheFileInfo(resourcePath, fileInfo, { importsMap, components, moduleId })
}
}
// 创建wxs文件
function createWxs (resourcePath, wxsContent, context, emitFile) {
const { filePath: wxsSrc } = getFiltersOutputSrc(context, resourcePath)
emitFile(wxsSrc, wxsContent)
}
// 分析mixins解析外部引用Filters
const cacheResolveMixinsFilters = {}
function resolveMixinsFilters (mixins, mixinsFilters, resolveFn, context, projectRoot, babelOptions, emitFile) {
return Promise.all(Object.keys(mixins).map(k => {
return new Promise((resolve, reject) => {
resolveFn(context, mixins[k], (err, realSrc) => {
if (err) return reject(err)
if (cacheResolveMixinsFilters[realSrc]) {
// 之前解析过该组件
mixinsFilters.push(realSrc)
} else {
// 之前未解析过该组件
// 读取文件
const mixinsFileSource = fs.readFileSync(realSrc).toString()
// 提取filters
const mixinsFileFilter = extractScriptFilters(mixinsFileSource, babelOptions)
if (mixinsFileFilter) {
mixinsFilters.push(realSrc)
cacheResolveMixinsFilters[realSrc] = mixinsFileFilter
// 创建引用的wxs文件
createWxs(realSrc, mixinsFileFilter.code, projectRoot, emitFile)
}
}
resolve()
})
})
}))
}
// 解析Filters
function resolveFilters (resourcePath, fileInfo, scriptContent, babelOptions, mixinsFilters, context, projectRoot, emitFile) {
const resourceSrcPath = getFiltersOutputSrc(projectRoot, resourcePath)
const mixinsFiltersArray = []
mixinsFilters.forEach((item) => {
// 计算相对路径,由于wxs里require只支持相对路径,微信真渣!
const itemSrcPath = getFiltersOutputSrc(projectRoot, item)
const realtivePath = path.join(path.relative(path.dirname(resourceSrcPath.filePath), path.dirname(itemSrcPath.filePath)), path.basename(itemSrcPath.filePath))
mixinsFiltersArray.push({
filePath: item,
name: itemSrcPath.name,
extractFilter: cacheResolveMixinsFilters[item],
realtivePath: realtivePath
})
})
// 提取脚本内的filters
const scriptFilter = extractScriptFilters(scriptContent, babelOptions)
// 合并外部引用和脚本内的filters
const combineFilter = combineScriptAndMixinsFilters(scriptFilter, mixinsFiltersArray, babelOptions)
// 保存文件信息
if (combineFilter) {
const filters = {
isCompleted: true,
src: path.join('./', path.basename(resourceSrcPath.filePath)),
module: resourceSrcPath.name
}
cacheFileInfo(resourcePath, fileInfo, { filters })
// 创建引用的wxs文件
createWxs(resourcePath, combineFilter.code, projectRoot, emitFile)
}
}
module.exports = { compileWxml, compileMPScript, compileMP }