-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshared.config.ts
207 lines (177 loc) · 5.91 KB
/
shared.config.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
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
import * as path from 'node:path';
import * as fs from 'node:fs';
import { createRequire } from 'node:module';
import { defineConfig } from 'vitest/config';
import type { UserConfig, ViteDevServer } from 'vite';
/**
* https://github.com/vuejs/core/issues/8303
* to fix error: ReferenceError: __name is not defined
*/
const __defProp = Object.defineProperty;
const __name = (target: any, value: any) => __defProp(target, 'name', { value, configurable: true });
globalThis.__name = globalThis.__name || __name;
const cwd = process.cwd();
// devOptions
const devOptions = JSON.parse(decodeURIComponent(process.env.DEV_OPTIONS || '{}'));
const { playDir, workspace, html, subpackagesMap } = devOptions;
const generateIndexHtml = (url: string, inject: string) => {
let contents = '';
contents += `<!DOCTYPE html>\n`;
contents += `<html lang="en">\n`;
contents += ` <head>\n`;
contents += ` <meta charset="UTF-8" />\n`;
contents += ` <meta name="viewport" content="width=device-width, initial-scale=1.0" />\n`;
contents += ` <title>demo-${url}</title>\n`;
contents += ` </head>\n`;
contents += ` <body>\n`;
contents += ` <div id="app"></div>\n`;
contents += ` <script type="module">\n`;
contents += inject;
contents += ` </script>\n`;
contents += ` </body>\n`;
contents += `</html>\n`;
return contents;
};
const getVirtualHtml = async (url: string) => {
const info = url.split('/').filter(i => !!i);
const prefix = info.slice(0, -1);
const entry = info.slice(-1)[0];
if (workspace && prefix[0] !== workspace) {
prefix.unshift(workspace);
}
const isExist = (ext: string) => {
const getFullpath = (dir: string) => path.join(dir, `${entry.replace(/(.*)(\..*)$/, '$1') + ext}`);
const last = prefix[prefix.length - 1];
const dirs = playDir.split(',');
if (dirs.some((i: string) => i === last)) {
const fullpath = getFullpath(path.join(cwd, prefix.join('/')));
return fs.existsSync(fullpath) ? fullpath : false;
}
for (let i = 0; i < dirs.length; i++) {
let suffix = dirs[i];
if (last === suffix) {
suffix = '';
}
const fullpath = getFullpath(path.join(cwd, prefix.concat([suffix]).join('/')));
if (fs.existsSync(fullpath)) {
return fullpath;
}
}
return false;
};
const getPreload = (fullpath: string) => {
let dir = path.dirname(fullpath);
let preload = '';
while (dir.includes(cwd) && !preload) {
const preloadFullPath = [
path.resolve(dir, './z.dev.preload.ts'),
path.resolve(dir, './dev.preload.ts'),
path.resolve(dir, './z.preload.ts'),
path.resolve(dir, './preload.ts')
].find(i => fs.existsSync(i));
if (preloadFullPath) {
preload = ` import "/${path.relative(cwd, preloadFullPath)}";\n`;
} else {
dir = path.resolve(dir, '..');
}
}
return preload;
};
const htmlFullpath = isExist('.html');
if (htmlFullpath) {
return fs.readFileSync(htmlFullpath).toString();
}
const tsFullpath = isExist('.ts');
if (tsFullpath) {
let inject = getPreload(tsFullpath);
inject += ` import "/${path.relative(cwd, tsFullpath)}";\n`;
return generateIndexHtml(url, inject);
}
const vueFullpath = isExist('.vue');
if (vueFullpath) {
let inject = getPreload(vueFullpath);
inject += ` import { createApp } from "vue"\n`;
inject += ` import App from "/${path.relative(cwd, vueFullpath)}";\n`;
inject += ` const app = createApp(App);\n`;
inject += ` app.mount("#app");\n`;
inject += ` typeof window !== "undefined" && (window.app = app);\n`;
return generateIndexHtml(url, inject);
}
const tsxFullpath = isExist('.tsx');
if (tsxFullpath) {
let inject = getPreload(tsxFullpath);
inject += ` import React, { StrictMode } from 'react';`;
inject += ` import { createRoot } from 'react-dom/client';`;
inject += ` import App from "/${path.relative(cwd, tsxFullpath)}";\n`;
inject += ` const h = React.createElement\n`;
inject += ` const app = createRoot(document.getElementById('app'));\n`;
inject += ` app.render(h(StrictMode, {}, h(App)))\n`;
return generateIndexHtml(url, inject);
}
};
// alias
const require$ = createRequire(cwd);
const getPackageName = (name: string) => (require$(path.resolve(cwd, workspace ? `${workspace}/${name}` : '', 'package.json'))).name;
const replacement = (name: string, isSubpackage?: boolean) => path.resolve(cwd, `./packages/${name}`, isSubpackage ? 'index.ts' : './src');
const name = getPackageName('index');
export default defineConfig({
resolve: workspace
? {
alias: [
{
find: new RegExp(`^${name}$`),
replacement: replacement('index')
},
...Object.keys(subpackagesMap).reduce((pre, cur: string) => {
if (subpackagesMap[cur].length) {
pre.push({
find: new RegExp(`^${getPackageName(cur)}$`),
replacement: replacement(cur, true)
});
}
return pre;
}, [] as any),
{
find: new RegExp(`^${name}-(.*?)$`),
replacement: replacement('$1')
}
]
}
: {},
plugins: [
{
name: 'vite-plugin-virtual-html',
configureServer(server: ViteDevServer) {
server.middlewares.use(async (req, res, next) => {
if (res.writableEnded) {
return next();
}
if (req.url!.includes('html-proxy&')) {
return next();
}
const url = req.url?.replace(/[?#].*$/s, '') || '';
if (url === '/') return res.end(html);
// 文件已存在,这样xxx.png可以被获取,真实路径的.ts,.html都可以被获取
if (fs.existsSync(path.join(cwd, url))) {
return next();
}
let vHtml = await getVirtualHtml(url);
if (
(url?.endsWith('.html') || vHtml)
&& req.headers['sec-fetch-dest'] !== 'script'
) {
if (!vHtml) {
return res.end(html);
}
vHtml = await server.transformIndexHtml(url, vHtml, req.originalUrl);
res.end(vHtml);
return;
}
next();
});
}
}
],
// 因为virtualHtml不需要入口,这样可以不弹出Skipping dependency pre-bundling.
optimizeDeps: { entries: [] }
}) as UserConfig;