-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
Copy pathentry.ts
96 lines (86 loc) · 2.57 KB
/
entry.ts
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
import fs from 'fs'
import path from 'path'
import {
addMiniProgramComponentJson,
normalizeMiniProgramFilename,
normalizePath,
removeExt,
encodeBase64Url,
decodeBase64Url,
parseJson,
} from '@dcloudio/uni-cli-shared'
import { Plugin } from 'vite'
import { UniMiniProgramPluginOptions } from '../plugin'
const uniPagePrefix = 'uniPage://'
const uniComponentPrefix = 'uniComponent://'
export function virtualPagePath(filepath: string) {
return uniPagePrefix + encodeBase64Url(filepath)
}
export function virtualComponentPath(filepath: string) {
return uniComponentPrefix + encodeBase64Url(filepath)
}
export function parseVirtualPagePath(uniPageUrl: string) {
return decodeBase64Url(uniPageUrl.replace(uniPagePrefix, ''))
}
export function parseVirtualComponentPath(uniComponentUrl: string) {
return decodeBase64Url(uniComponentUrl.replace(uniComponentPrefix, ''))
}
export function isUniPageUrl(id: string) {
return id.startsWith(uniPagePrefix)
}
export function isUniComponentUrl(id: string) {
return id.startsWith(uniComponentPrefix)
}
export function parseComponentJson(filepath: string) {
const jsonPath = filepath.replace(/\.[^.]+$/, '.json')
if (fs.existsSync(jsonPath)) {
const json = parseJson(fs.readFileSync(jsonPath, 'utf8'))
return json[process.env.UNI_PLATFORM]
}
}
export function uniEntryPlugin({
global,
}: UniMiniProgramPluginOptions): Plugin {
const inputDir = process.env.UNI_INPUT_DIR
return {
name: 'uni:virtual',
enforce: 'pre',
resolveId(id) {
if (isUniPageUrl(id) || isUniComponentUrl(id)) {
return id
}
},
load(id) {
if (isUniPageUrl(id)) {
const filepath = normalizePath(
path.resolve(inputDir, parseVirtualPagePath(id))
)
this.addWatchFile(filepath)
return {
code: `import MiniProgramPage from '${filepath}'
${global}.createPage(MiniProgramPage)`,
}
} else if (isUniComponentUrl(id)) {
const filepath = normalizePath(
path.resolve(inputDir, parseVirtualComponentPath(id))
)
this.addWatchFile(filepath)
addMiniProgramComponentJson(
removeExt(normalizeMiniProgramFilename(filepath, inputDir)),
{
component: true,
styleIsolation:
process.env.UNI_PLATFORM === 'mp-baidu'
? 'apply-shared'
: undefined,
...parseComponentJson(filepath),
}
)
return {
code: `import Component from '${filepath}'
${global}.createComponent(Component)`,
}
}
},
}
}