@fchc8/vite-plugin-multi-page 1.7.1 → 1.8.0
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.
- package/dist/cli.js +17 -901
- package/dist/index.js +22 -792
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +21 -749
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,261 +1,14 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
// src/dev-server.ts
|
|
6
|
-
import * as path2 from "node:path";
|
|
7
|
-
import * as fs from "node:fs";
|
|
8
|
-
import { glob } from "glob";
|
|
9
|
-
|
|
10
|
-
// src/file-filter.ts
|
|
11
|
-
import * as path from "node:path";
|
|
12
|
-
function filterEntryFiles(files, entry, exclude, _log) {
|
|
13
|
-
const result = [];
|
|
14
|
-
const nameToFile = /* @__PURE__ */ new Map();
|
|
15
|
-
let basePattern = entry.replace(/\/\*.*$/, "");
|
|
16
|
-
if (!basePattern || basePattern === entry) {
|
|
17
|
-
basePattern = path.dirname(entry.split("*")[0]);
|
|
18
|
-
}
|
|
19
|
-
const candidateFiles = [];
|
|
20
|
-
for (const file of files) {
|
|
21
|
-
if (exclude.includes(file)) {
|
|
22
|
-
continue;
|
|
23
|
-
}
|
|
24
|
-
const relativePath = path.relative(basePattern, file);
|
|
25
|
-
const pathParts = relativePath.split(path.sep);
|
|
26
|
-
if (pathParts.length === 1) {
|
|
27
|
-
const fileName = pathParts[0];
|
|
28
|
-
const name = path.basename(fileName, path.extname(fileName));
|
|
29
|
-
candidateFiles.push({ name, file, priority: 1 });
|
|
30
|
-
} else if (pathParts.length >= 2) {
|
|
31
|
-
const fileName = path.basename(file, path.extname(file));
|
|
32
|
-
const dirName = pathParts[0];
|
|
33
|
-
if (fileName === "main") {
|
|
34
|
-
candidateFiles.push({ name: dirName, file, priority: 2 });
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
for (const candidate of candidateFiles) {
|
|
39
|
-
const existing = nameToFile.get(candidate.name);
|
|
40
|
-
if (!existing) {
|
|
41
|
-
nameToFile.set(candidate.name, { file: candidate.file, priority: candidate.priority });
|
|
42
|
-
} else {
|
|
43
|
-
if (candidate.priority > existing.priority) {
|
|
44
|
-
nameToFile.set(candidate.name, { file: candidate.file, priority: candidate.priority });
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
for (const [name, { file }] of nameToFile.entries()) {
|
|
49
|
-
result.push({ name, file });
|
|
50
|
-
}
|
|
51
|
-
return result;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
// src/utils.ts
|
|
55
|
-
function escapeRegExp(string) {
|
|
56
|
-
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
57
|
-
}
|
|
58
|
-
function createLogger(debug) {
|
|
59
|
-
return (...args) => {
|
|
60
|
-
if (debug) {
|
|
61
|
-
console.log("[vite-plugin-multi-page]", ...args);
|
|
62
|
-
}
|
|
63
|
-
};
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
// src/page-config.ts
|
|
67
|
-
function getPageConfig(pageConfigs, context, log) {
|
|
68
|
-
if (!pageConfigs)
|
|
69
|
-
return null;
|
|
70
|
-
if (typeof pageConfigs === "function") {
|
|
71
|
-
const result = pageConfigs(context);
|
|
72
|
-
if (result) {
|
|
73
|
-
}
|
|
74
|
-
return result;
|
|
75
|
-
}
|
|
76
|
-
for (const [key, config] of Object.entries(pageConfigs)) {
|
|
77
|
-
if (key === context.pageName) {
|
|
78
|
-
log(`\u7CBE\u786E\u5339\u914D\u9875\u9762 ${context.pageName}:`, config);
|
|
79
|
-
return config;
|
|
80
|
-
}
|
|
81
|
-
if (config.match) {
|
|
82
|
-
const patterns = Array.isArray(config.match) ? config.match : [config.match];
|
|
83
|
-
const isMatched = patterns.some(
|
|
84
|
-
(pattern) => simpleMatch(pattern, context.pageName) || simpleMatch(pattern, context.relativePath) || simpleMatch(pattern, context.filePath)
|
|
85
|
-
);
|
|
86
|
-
if (isMatched) {
|
|
87
|
-
log(`\u6A21\u5F0F\u5339\u914D\u9875\u9762 ${context.pageName} (\u6A21\u5F0F: ${config.match}):`, config);
|
|
88
|
-
return { ...config, match: void 0 };
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
if (simpleMatch(key, context.pageName)) {
|
|
92
|
-
log(`Glob\u5339\u914D\u9875\u9762 ${context.pageName} (\u6A21\u5F0F: ${key}):`, config);
|
|
93
|
-
return config;
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
return null;
|
|
97
|
-
}
|
|
98
|
-
function simpleMatch(pattern, text) {
|
|
99
|
-
const regexPattern = pattern.replace(/\*\*/g, "__DOUBLE_STAR__").replace(/\*/g, "[^/]*").replace(/__DOUBLE_STAR__/g, ".*");
|
|
100
|
-
const regex = new RegExp(`^${regexPattern}$`);
|
|
101
|
-
return regex.test(text);
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
// src/dev-server.ts
|
|
105
|
-
function configureDevServer(server, options, log) {
|
|
106
|
-
try {
|
|
107
|
-
const allFiles = glob.sync(options.entry, { cwd: process.cwd() });
|
|
108
|
-
let entryFiles = filterEntryFiles(allFiles, options.entry, options.exclude, log);
|
|
109
|
-
if (entryFiles.length === 0) {
|
|
110
|
-
log("\u8B66\u544A: \u672A\u627E\u5230\u5339\u914D\u7684\u5165\u53E3\u6587\u4EF6");
|
|
111
|
-
return;
|
|
112
|
-
}
|
|
113
|
-
const cliStrategy = server.config.__cliStrategy || server.config.strategy;
|
|
114
|
-
if (cliStrategy) {
|
|
115
|
-
log(`\u5F00\u53D1\u670D\u52A1\u5668\u4F7F\u7528\u6307\u5B9A\u7684\u7B56\u7565: ${cliStrategy}`);
|
|
116
|
-
entryFiles = entryFiles.filter((file) => {
|
|
117
|
-
var _a;
|
|
118
|
-
const pageName = file.name;
|
|
119
|
-
const pageStrategy = ((_a = options.appliedStrategies) == null ? void 0 : _a.get(pageName)) || void 0;
|
|
120
|
-
if (cliStrategy === "default") {
|
|
121
|
-
return !pageStrategy || pageStrategy === "default";
|
|
122
|
-
}
|
|
123
|
-
return pageStrategy === cliStrategy;
|
|
124
|
-
});
|
|
125
|
-
log(`\u7B56\u7565 "${cliStrategy}" \u4E0B\u53EF\u7528\u7684\u9875\u9762: ${entryFiles.map((f) => f.name).join(", ") || "\u65E0"}`);
|
|
126
|
-
}
|
|
127
|
-
log("\u5F00\u53D1\u670D\u52A1\u5668\u5E94\u7528\u7684\u5165\u53E3\u6587\u4EF6:", entryFiles);
|
|
128
|
-
server.middlewares.use(async (req, res, next) => {
|
|
129
|
-
var _a;
|
|
130
|
-
try {
|
|
131
|
-
const url = req.url || "";
|
|
132
|
-
const pathWithoutQuery = url.split("?")[0];
|
|
133
|
-
if (pathWithoutQuery === "/") {
|
|
134
|
-
const indexHtml = generateIndexHtml(entryFiles, options, log);
|
|
135
|
-
res.statusCode = 200;
|
|
136
|
-
res.setHeader("Content-Type", "text/html");
|
|
137
|
-
res.end(indexHtml);
|
|
138
|
-
return;
|
|
139
|
-
}
|
|
140
|
-
if (pathWithoutQuery.match(/\.(js|css|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot)$/) && !pathWithoutQuery.endsWith(".html")) {
|
|
141
|
-
return next();
|
|
142
|
-
}
|
|
143
|
-
let pageName = "";
|
|
144
|
-
if (pathWithoutQuery.endsWith(".html")) {
|
|
145
|
-
pageName = path2.basename(pathWithoutQuery, ".html");
|
|
146
|
-
} else if (pathWithoutQuery.startsWith("/")) {
|
|
147
|
-
pageName = pathWithoutQuery.substring(1);
|
|
148
|
-
}
|
|
149
|
-
if (!pageName) {
|
|
150
|
-
return next();
|
|
151
|
-
}
|
|
152
|
-
const matchedFile = entryFiles.find((file) => file.name === pageName);
|
|
153
|
-
if (!matchedFile) {
|
|
154
|
-
return next();
|
|
155
|
-
}
|
|
156
|
-
const pageContext = {
|
|
157
|
-
pageName: matchedFile.name,
|
|
158
|
-
filePath: matchedFile.file,
|
|
159
|
-
relativePath: path2.relative(process.cwd(), matchedFile.file),
|
|
160
|
-
strategy: void 0,
|
|
161
|
-
isMatched: false
|
|
162
|
-
};
|
|
163
|
-
const pageConfig = getPageConfig(options.pageConfigs, pageContext, log);
|
|
164
|
-
if (pageConfig == null ? void 0 : pageConfig.strategy) {
|
|
165
|
-
pageContext.strategy = pageConfig.strategy;
|
|
166
|
-
} else if ((_a = options.appliedStrategies) == null ? void 0 : _a.has(pageName)) {
|
|
167
|
-
const strategyName = options.appliedStrategies.get(pageName);
|
|
168
|
-
if (strategyName) {
|
|
169
|
-
pageContext.strategy = strategyName;
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
let templatePath = "";
|
|
173
|
-
const pageSpecificTemplate = path2.resolve(process.cwd(), `${pageName}.html`);
|
|
174
|
-
if (fs.existsSync(pageSpecificTemplate)) {
|
|
175
|
-
templatePath = pageSpecificTemplate;
|
|
176
|
-
} else if (pageConfig == null ? void 0 : pageConfig.template) {
|
|
177
|
-
templatePath = path2.resolve(process.cwd(), pageConfig.template);
|
|
178
|
-
} else {
|
|
179
|
-
templatePath = path2.resolve(process.cwd(), options.template);
|
|
180
|
-
}
|
|
181
|
-
if (!fs.existsSync(templatePath)) {
|
|
182
|
-
return next();
|
|
183
|
-
}
|
|
184
|
-
let html = fs.readFileSync(templatePath, "utf-8");
|
|
185
|
-
const containsPlaceholder = html.includes(options.placeholder);
|
|
186
|
-
if (containsPlaceholder) {
|
|
187
|
-
const originalHtml = html;
|
|
188
|
-
html = html.split(options.placeholder).join(`/${matchedFile.file}`);
|
|
189
|
-
if (html === originalHtml) {
|
|
190
|
-
const escapedPlaceholder = escapeRegExp(options.placeholder);
|
|
191
|
-
const placeholderRegex = new RegExp(escapedPlaceholder, "g");
|
|
192
|
-
html = originalHtml.replace(placeholderRegex, `/${matchedFile.file}`);
|
|
193
|
-
if (html === originalHtml) {
|
|
194
|
-
html = originalHtml.replace(/\{\{ENTRY_FILE\}\}/g, `/${matchedFile.file}`);
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
if (pageConfig == null ? void 0 : pageConfig.define) {
|
|
199
|
-
const defineScript = Object.entries(pageConfig.define).map(([key, value]) => {
|
|
200
|
-
const stringValue = typeof value === "string" ? `"${value}"` : JSON.stringify(value);
|
|
201
|
-
return `window.${key} = ${stringValue};`;
|
|
202
|
-
}).join("\n");
|
|
203
|
-
if (defineScript) {
|
|
204
|
-
html = html.replace(
|
|
205
|
-
/<\/head>/i,
|
|
206
|
-
`<script type="text/javascript">
|
|
207
|
-
${defineScript}
|
|
1
|
+
import*as N from"node:fs";import{mergeConfig as ae}from"vite";import*as C from"node:path";import*as _ from"node:fs";import{glob as J}from"glob";import*as P from"node:path";function T(t,e,s,i){let n=[],a=new Map,g=e.replace(/\/\*.*$/,"");(!g||g===e)&&(g=P.dirname(e.split("*")[0]));let l=[];for(let r of t){if(s.includes(r))continue;let o=r.replace(/\\/g,"/"),c=g.replace(/\\/g,"/"),p=P.posix.relative(c,o).split("/");if(p.length===1){let m=p[0],u=P.posix.basename(m,P.posix.extname(m));l.push({name:u,file:r,priority:1})}else if(p.length>=2){let m=P.posix.basename(o,P.posix.extname(o)),u=p[0];m==="main"&&l.push({name:u,file:r,priority:2})}}for(let r of l){let o=a.get(r.name);o?r.priority>o.priority&&a.set(r.name,{file:r.file,priority:r.priority}):a.set(r.name,{file:r.file,priority:r.priority})}for(let[r,{file:o}]of a.entries())n.push({name:r,file:o});return n}function Y(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function M(t){return(...e)=>{t&&console.log("[vite-plugin-multi-page]",...e)}}function O(t,e,s){if(!t)return null;if(typeof t=="function"){let i=t(e);return i}for(let[i,n]of Object.entries(t)){if(i===e.pageName)return s(`\u7CBE\u786E\u5339\u914D\u9875\u9762 ${e.pageName}:`,n),n;if(n.match&&(Array.isArray(n.match)?n.match:[n.match]).some(l=>I(l,e.pageName)||I(l,e.relativePath)||I(l,e.filePath)))return s(`\u6A21\u5F0F\u5339\u914D\u9875\u9762 ${e.pageName} (\u6A21\u5F0F: ${n.match}):`,n),{...n,match:void 0};if(I(i,e.pageName))return s(`Glob\u5339\u914D\u9875\u9762 ${e.pageName} (\u6A21\u5F0F: ${i}):`,n),n}return null}function I(t,e){let s=t.replace(/\*\*/g,"__DOUBLE_STAR__").replace(/\*/g,"[^/]*").replace(/__DOUBLE_STAR__/g,".*");return new RegExp(`^${s}$`).test(e)}function Q(t,e,s){try{let i=J.sync(e.entry,{cwd:process.cwd()}),n=T(i,e.entry,e.exclude,s);if(n.length===0){s("\u8B66\u544A: \u672A\u627E\u5230\u5339\u914D\u7684\u5165\u53E3\u6587\u4EF6");return}let a=e.devStrategy||t.config.__cliStrategy||t.config.strategy;a&&(s(`\u5F00\u53D1\u670D\u52A1\u5668\u4F7F\u7528\u6307\u5B9A\u7684\u7B56\u7565: ${a}`),n=n.filter(g=>{let l={pageName:g.name,filePath:g.file,relativePath:C.relative(process.cwd(),g.file),strategy:void 0,isMatched:!1},r=O(e.pageConfigs,l,s),o=(r==null?void 0:r.strategy)||"default";return a==="default"?o==="default":o===a}),s(`\u7B56\u7565 "${a}" \u4E0B\u53EF\u7528\u7684\u9875\u9762: ${n.map(g=>g.name).join(", ")||"\u65E0"}`)),s("\u5F00\u53D1\u670D\u52A1\u5668\u5E94\u7528\u7684\u5165\u53E3\u6587\u4EF6:",n),t.middlewares.use(async(g,l,r)=>{try{let c=(g.url||"").split("?")[0];if(c==="/"){let m=X(n,e,s);l.statusCode=200,l.setHeader("Content-Type","text/html"),l.end(m);return}if(c.match(/\.(js|css|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot)$/)&&!c.endsWith(".html"))return r();let f="";if(c.endsWith(".html")?f=C.basename(c,".html"):c.startsWith("/")&&(f=c.substring(1)),!f)return r();let p=n.find(m=>m.name===f);return p?K(l,p,e,s):r()}catch(o){s(`\u5F00\u53D1\u670D\u52A1\u5668\u5904\u7406\u8BF7\u6C42\u5931\u8D25: ${o}`),r(o)}}),s("\u5F00\u53D1\u670D\u52A1\u5668\u914D\u7F6E\u5B8C\u6210")}catch(i){throw s(`\u914D\u7F6E\u5F00\u53D1\u670D\u52A1\u5668\u5931\u8D25: ${i}`),i}}function K(t,e,s,i){var c;let n={pageName:e.name,filePath:e.file,relativePath:C.relative(process.cwd(),e.file),strategy:void 0,isMatched:!1},a=O(s.pageConfigs,n,i);if(a!=null&&a.strategy)n.strategy=a.strategy;else if((c=s.appliedStrategies)!=null&&c.has(e.name)){let f=s.appliedStrategies.get(e.name);f&&(n.strategy=f)}let g="",l=C.resolve(process.cwd(),`${e.name}.html`);if(_.existsSync(l)?g=l:a!=null&&a.template?g=C.resolve(process.cwd(),a.template):g=C.resolve(process.cwd(),s.template),!_.existsSync(g)){t.statusCode=404,t.end("Template not found");return}let r=_.readFileSync(g,"utf-8");if(r.includes(s.placeholder)){let f=r;if(r=r.split(s.placeholder).join(`/${e.file}`),r===f){let p=Y(s.placeholder),m=new RegExp(p,"g");r=f.replace(m,`/${e.file}`),r===f&&(r=f.replace(/\{\{ENTRY_FILE\}\}/g,`/${e.file}`))}}if(a!=null&&a.define){let f=Object.entries(a.define).map(([p,m])=>{let u=typeof m=="string"?`"${m}"`:JSON.stringify(m);return`window.${p} = ${u};`}).join(`
|
|
2
|
+
`);f&&(r=r.replace(/<\/head>/i,`<script type="text/javascript">
|
|
3
|
+
${f}
|
|
208
4
|
</script>
|
|
209
|
-
</head>`
|
|
210
|
-
);
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
res.statusCode = 200;
|
|
214
|
-
res.setHeader("Content-Type", "text/html");
|
|
215
|
-
res.end(html);
|
|
216
|
-
} catch (error) {
|
|
217
|
-
log(`\u5F00\u53D1\u670D\u52A1\u5668\u5904\u7406\u8BF7\u6C42\u5931\u8D25: ${error}`);
|
|
218
|
-
next(error);
|
|
219
|
-
}
|
|
220
|
-
});
|
|
221
|
-
log("\u5F00\u53D1\u670D\u52A1\u5668\u914D\u7F6E\u5B8C\u6210");
|
|
222
|
-
} catch (error) {
|
|
223
|
-
log(`\u914D\u7F6E\u5F00\u53D1\u670D\u52A1\u5668\u5931\u8D25: ${error}`);
|
|
224
|
-
throw error;
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
var setupDevMiddleware = configureDevServer;
|
|
228
|
-
function generateIndexHtml(entryFiles, options, log) {
|
|
229
|
-
try {
|
|
230
|
-
const pageItems = entryFiles.map((file) => {
|
|
231
|
-
var _a;
|
|
232
|
-
const pageContext = {
|
|
233
|
-
pageName: file.name,
|
|
234
|
-
filePath: file.file,
|
|
235
|
-
relativePath: path2.relative(process.cwd(), file.file),
|
|
236
|
-
strategy: void 0,
|
|
237
|
-
isMatched: false
|
|
238
|
-
};
|
|
239
|
-
const pageConfig = getPageConfig(options.pageConfigs, pageContext, log);
|
|
240
|
-
let strategy = "default";
|
|
241
|
-
if (pageConfig == null ? void 0 : pageConfig.strategy) {
|
|
242
|
-
strategy = pageConfig.strategy;
|
|
243
|
-
} else if ((_a = options.appliedStrategies) == null ? void 0 : _a.has(file.name)) {
|
|
244
|
-
const strategyName = options.appliedStrategies.get(file.name);
|
|
245
|
-
if (strategyName) {
|
|
246
|
-
strategy = strategyName;
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
const strategyBadge = strategy !== "default" ? `<span class="badge">${strategy}</span>` : "";
|
|
250
|
-
return `
|
|
5
|
+
</head>`))}t.statusCode=200,t.setHeader("Content-Type","text/html"),t.end(r)}var W=Q;function X(t,e,s){try{let i=t.map(n=>{var o;let a={pageName:n.name,filePath:n.file,relativePath:C.relative(process.cwd(),n.file),strategy:void 0,isMatched:!1},g=O(e.pageConfigs,a,s),l="default";if(g!=null&&g.strategy)l=g.strategy;else if((o=e.appliedStrategies)!=null&&o.has(n.name)){let c=e.appliedStrategies.get(n.name);c&&(l=c)}let r=l!=="default"?`<span class="badge">${l}</span>`:"";return`
|
|
251
6
|
<div class="page-item">
|
|
252
|
-
<a href="${
|
|
253
|
-
${
|
|
7
|
+
<a href="${n.name}.html" class="page-link">
|
|
8
|
+
${n.name}${r}
|
|
254
9
|
</a>
|
|
255
|
-
<div class="page-path">${
|
|
256
|
-
</div
|
|
257
|
-
}).join("");
|
|
258
|
-
return `
|
|
10
|
+
<div class="page-path">${n.file}</div>
|
|
11
|
+
</div>`}).join("");return`
|
|
259
12
|
<!DOCTYPE html>
|
|
260
13
|
<html lang="en">
|
|
261
14
|
<head>
|
|
@@ -327,17 +80,14 @@ function generateIndexHtml(entryFiles, options, log) {
|
|
|
327
80
|
<body>
|
|
328
81
|
<h1>\u591A\u9875\u9762\u5E94\u7528\u7D22\u5F15</h1>
|
|
329
82
|
<div class="stats">
|
|
330
|
-
\u627E\u5230 ${
|
|
83
|
+
\u627E\u5230 ${t.length} \u4E2A\u9875\u9762
|
|
331
84
|
</div>
|
|
332
85
|
<div class="page-list">
|
|
333
|
-
${
|
|
86
|
+
${i}
|
|
334
87
|
</div>
|
|
335
88
|
</body>
|
|
336
89
|
</html>
|
|
337
|
-
|
|
338
|
-
} catch (error) {
|
|
339
|
-
log(`\u751F\u6210\u7D22\u5F15\u9875\u5931\u8D25: ${error}`);
|
|
340
|
-
return `
|
|
90
|
+
`}catch(i){return s(`\u751F\u6210\u7D22\u5F15\u9875\u5931\u8D25: ${i}`),`
|
|
341
91
|
<!DOCTYPE html>
|
|
342
92
|
<html>
|
|
343
93
|
<head>
|
|
@@ -345,501 +95,23 @@ function generateIndexHtml(entryFiles, options, log) {
|
|
|
345
95
|
</head>
|
|
346
96
|
<body>
|
|
347
97
|
<h1>\u751F\u6210\u7D22\u5F15\u9875\u65F6\u53D1\u751F\u9519\u8BEF</h1>
|
|
348
|
-
<p>${
|
|
98
|
+
<p>${i}</p>
|
|
349
99
|
</body>
|
|
350
100
|
</html>
|
|
351
|
-
`;
|
|
352
|
-
}
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
// src/build-config.ts
|
|
356
|
-
import { mergeConfig } from "vite";
|
|
357
|
-
import { glob as glob2 } from "glob";
|
|
358
|
-
import * as path3 from "node:path";
|
|
359
|
-
import * as fs2 from "node:fs";
|
|
360
|
-
function generateBuildConfig(options) {
|
|
361
|
-
var _a;
|
|
362
|
-
const {
|
|
363
|
-
entry = "src/pages/*/main.{ts,js}",
|
|
364
|
-
exclude = [],
|
|
365
|
-
template = "index.html",
|
|
366
|
-
placeholder = "<!--VITE_MULTI_PAGE_ENTRY-->",
|
|
367
|
-
strategies = {},
|
|
368
|
-
pageConfigs = {},
|
|
369
|
-
forceBuildStrategy
|
|
370
|
-
} = options;
|
|
371
|
-
const log = createLogger(true);
|
|
372
|
-
const buildConfigs = {};
|
|
373
|
-
try {
|
|
374
|
-
const allFiles = glob2.sync(entry, { cwd: process.cwd() });
|
|
375
|
-
const entryFiles = filterEntryFiles(allFiles, entry, exclude, log);
|
|
376
|
-
if (entryFiles.length === 0) {
|
|
377
|
-
log("\u8B66\u544A: \u672A\u627E\u5230\u5339\u914D\u7684\u5165\u53E3\u6587\u4EF6");
|
|
378
|
-
return {};
|
|
379
|
-
}
|
|
380
|
-
const pageStrategies = /* @__PURE__ */ new Map();
|
|
381
|
-
const strategyPages = /* @__PURE__ */ new Map();
|
|
382
|
-
for (const entryFile of entryFiles) {
|
|
383
|
-
const pageContext = {
|
|
384
|
-
pageName: entryFile.name,
|
|
385
|
-
filePath: entryFile.file,
|
|
386
|
-
relativePath: path3.relative(process.cwd(), entryFile.file)
|
|
387
|
-
};
|
|
388
|
-
const pageConfig = getPageConfig(pageConfigs, pageContext, log);
|
|
389
|
-
const strategyName = (pageConfig == null ? void 0 : pageConfig.strategy) || "default";
|
|
390
|
-
pageStrategies.set(entryFile.name, strategyName);
|
|
391
|
-
if (!strategyPages.has(strategyName)) {
|
|
392
|
-
strategyPages.set(strategyName, []);
|
|
393
|
-
}
|
|
394
|
-
(_a = strategyPages.get(strategyName)) == null ? void 0 : _a.push(entryFile.name);
|
|
395
|
-
}
|
|
396
|
-
log(`\u{1F4C4} \u53D1\u73B0 ${entryFiles.length} \u4E2A\u9875\u9762: ${entryFiles.map((f) => f.name).join(", ")}`);
|
|
397
|
-
if (forceBuildStrategy) {
|
|
398
|
-
const targetPages = strategyPages.get(forceBuildStrategy) || [];
|
|
399
|
-
if (targetPages.length === 0) {
|
|
400
|
-
log(`\u8B66\u544A: \u7B56\u7565 "${forceBuildStrategy}" \u4E0B\u6CA1\u6709\u9875\u9762`);
|
|
401
|
-
return {};
|
|
402
|
-
}
|
|
403
|
-
log(`\u5F3A\u5236\u6784\u5EFA\u7B56\u7565: ${forceBuildStrategy}, \u9875\u9762: ${targetPages.join(", ")}`);
|
|
404
|
-
const config = generateStrategyConfig(
|
|
405
|
-
forceBuildStrategy,
|
|
406
|
-
targetPages,
|
|
407
|
-
entryFiles,
|
|
408
|
-
strategies[forceBuildStrategy],
|
|
409
|
-
pageConfigs,
|
|
410
|
-
template,
|
|
411
|
-
placeholder,
|
|
412
|
-
log
|
|
413
|
-
);
|
|
414
|
-
buildConfigs[forceBuildStrategy] = config;
|
|
415
|
-
return buildConfigs;
|
|
416
|
-
}
|
|
417
|
-
for (const [strategyName, pages] of strategyPages) {
|
|
418
|
-
if (pages.length === 0)
|
|
419
|
-
continue;
|
|
420
|
-
const strategyConfig = strategies[strategyName] || {};
|
|
421
|
-
const config = generateStrategyConfig(
|
|
422
|
-
strategyName,
|
|
423
|
-
pages,
|
|
424
|
-
entryFiles,
|
|
425
|
-
strategyConfig,
|
|
426
|
-
pageConfigs,
|
|
427
|
-
template,
|
|
428
|
-
placeholder,
|
|
429
|
-
log
|
|
430
|
-
);
|
|
431
|
-
buildConfigs[strategyName] = config;
|
|
432
|
-
}
|
|
433
|
-
if (Object.keys(buildConfigs).length === 0) {
|
|
434
|
-
log("\u8B66\u544A: \u672A\u751F\u6210\u4EFB\u4F55\u6784\u5EFA\u914D\u7F6E\uFF0C\u521B\u5EFA\u9ED8\u8BA4\u914D\u7F6E");
|
|
435
|
-
const allPageNames = entryFiles.map((f) => f.name);
|
|
436
|
-
const defaultConfig = generateStrategyConfig(
|
|
437
|
-
"default",
|
|
438
|
-
allPageNames,
|
|
439
|
-
entryFiles,
|
|
440
|
-
{},
|
|
441
|
-
pageConfigs,
|
|
442
|
-
template,
|
|
443
|
-
placeholder,
|
|
444
|
-
log
|
|
445
|
-
);
|
|
446
|
-
buildConfigs["default"] = defaultConfig;
|
|
447
|
-
}
|
|
448
|
-
const strategyNames = Object.keys(buildConfigs);
|
|
449
|
-
log(`\u{1F4E6} \u6784\u5EFA\u7B56\u7565: ${strategyNames.join(", ")}`);
|
|
450
|
-
return buildConfigs;
|
|
451
|
-
} catch (error) {
|
|
452
|
-
log("\u751F\u6210\u6784\u5EFA\u914D\u7F6E\u5931\u8D25:", error);
|
|
453
|
-
throw error;
|
|
454
|
-
}
|
|
455
|
-
}
|
|
456
|
-
function generateStrategyConfig(strategyName, pages, entryFiles, strategyConfig, pageConfigs, defaultTemplate, placeholder, log) {
|
|
457
|
-
const htmlInputs = {};
|
|
458
|
-
const tempFiles = [];
|
|
459
|
-
const allPageDefines = {};
|
|
460
|
-
for (const pageName of pages) {
|
|
461
|
-
const entryFile = entryFiles.find((f) => f.name === pageName);
|
|
462
|
-
if (!entryFile)
|
|
463
|
-
continue;
|
|
464
|
-
const pageContext = {
|
|
465
|
-
pageName,
|
|
466
|
-
filePath: entryFile.file,
|
|
467
|
-
relativePath: path3.relative(process.cwd(), entryFile.file),
|
|
468
|
-
strategy: strategyName
|
|
469
|
-
};
|
|
470
|
-
const pageConfig = getPageConfig(pageConfigs, pageContext, log);
|
|
471
|
-
if (pageConfig == null ? void 0 : pageConfig.define) {
|
|
472
|
-
Object.assign(allPageDefines, pageConfig.define);
|
|
473
|
-
}
|
|
474
|
-
let templatePath = defaultTemplate;
|
|
475
|
-
const pageSpecificTemplate = `${pageName}.html`;
|
|
476
|
-
if (fs2.existsSync(path3.resolve(process.cwd(), pageSpecificTemplate))) {
|
|
477
|
-
templatePath = pageSpecificTemplate;
|
|
478
|
-
} else if (pageConfig == null ? void 0 : pageConfig.template) {
|
|
479
|
-
templatePath = pageConfig.template;
|
|
480
|
-
}
|
|
481
|
-
const templateFullPath = path3.resolve(process.cwd(), templatePath);
|
|
482
|
-
if (!fs2.existsSync(templateFullPath)) {
|
|
483
|
-
log(`\u8B66\u544A: \u6A21\u677F\u6587\u4EF6\u4E0D\u5B58\u5728: ${templatePath}`);
|
|
484
|
-
continue;
|
|
485
|
-
}
|
|
486
|
-
let templateContent = fs2.readFileSync(templateFullPath, "utf-8");
|
|
487
|
-
if (templateContent.includes(placeholder)) {
|
|
488
|
-
const entryPath = `./${entryFile.file}`;
|
|
489
|
-
templateContent = templateContent.replace(
|
|
490
|
-
new RegExp(placeholder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"),
|
|
491
|
-
entryPath
|
|
492
|
-
);
|
|
493
|
-
}
|
|
494
|
-
const tempHtmlPath = path3.resolve(process.cwd(), `.temp.mp.${pageName}.html`);
|
|
495
|
-
fs2.writeFileSync(tempHtmlPath, templateContent);
|
|
496
|
-
tempFiles.push(tempHtmlPath);
|
|
497
|
-
htmlInputs[pageName] = tempHtmlPath;
|
|
498
|
-
}
|
|
499
|
-
const baseConfig = {
|
|
500
|
-
build: {
|
|
501
|
-
rollupOptions: {
|
|
502
|
-
input: htmlInputs,
|
|
503
|
-
// 使用临时HTML文件作为输入
|
|
504
|
-
output: {
|
|
505
|
-
entryFileNames: "assets/[name]-[hash].js",
|
|
506
|
-
chunkFileNames: "assets/[name]-[hash].js",
|
|
507
|
-
assetFileNames: "assets/[name]-[hash][extname]"
|
|
508
|
-
}
|
|
509
|
-
},
|
|
510
|
-
emptyOutDir: false
|
|
511
|
-
// 不清空输出目录,避免删除临时HTML文件
|
|
512
|
-
},
|
|
513
|
-
define: {}
|
|
514
|
-
};
|
|
515
|
-
let config = baseConfig;
|
|
516
|
-
if (strategyConfig) {
|
|
517
|
-
config = mergeConfig(baseConfig, strategyConfig);
|
|
518
|
-
}
|
|
519
|
-
if (Object.keys(allPageDefines).length > 0) {
|
|
520
|
-
config.define = {
|
|
521
|
-
...config.define,
|
|
522
|
-
...allPageDefines
|
|
523
|
-
};
|
|
524
|
-
}
|
|
525
|
-
if (!config.build)
|
|
526
|
-
config.build = {};
|
|
527
|
-
if (!config.build.rollupOptions)
|
|
528
|
-
config.build.rollupOptions = {};
|
|
529
|
-
config.build.rollupOptions.input = htmlInputs;
|
|
530
|
-
config.build.emptyOutDir = false;
|
|
531
|
-
log(`\u7B56\u7565 "${strategyName}" - ${pages.length} \u4E2A\u9875\u9762`);
|
|
532
|
-
return config;
|
|
533
|
-
}
|
|
534
|
-
function getViteOutputDirectory(viteBuildArgs = []) {
|
|
535
|
-
const outDirIndex = viteBuildArgs.findIndex((arg) => arg === "--outDir");
|
|
536
|
-
if (outDirIndex !== -1 && outDirIndex + 1 < viteBuildArgs.length) {
|
|
537
|
-
const outDir = viteBuildArgs[outDirIndex + 1];
|
|
538
|
-
return path3.resolve(process.cwd(), outDir);
|
|
539
|
-
}
|
|
540
|
-
const outDirArg = viteBuildArgs.find((arg) => arg.startsWith("--outDir="));
|
|
541
|
-
if (outDirArg) {
|
|
542
|
-
const outDir = outDirArg.split("=")[1];
|
|
543
|
-
return path3.resolve(process.cwd(), outDir);
|
|
544
|
-
}
|
|
545
|
-
return path3.resolve(process.cwd(), "dist");
|
|
546
|
-
}
|
|
547
|
-
function cleanViteOutputDirectory(viteBuildArgs = []) {
|
|
548
|
-
const outputDir = getViteOutputDirectory(viteBuildArgs);
|
|
549
|
-
const log = createLogger(true);
|
|
550
|
-
try {
|
|
551
|
-
if (fs2.existsSync(outputDir)) {
|
|
552
|
-
fs2.rmSync(outputDir, { recursive: true, force: true });
|
|
553
|
-
log(`\u{1F9F9} \u6E05\u7406\u8F93\u51FA\u76EE\u5F55: ${path3.relative(process.cwd(), outputDir)}`);
|
|
554
|
-
}
|
|
555
|
-
} catch (error) {
|
|
556
|
-
log(`\u26A0\uFE0F \u6E05\u7406\u8F93\u51FA\u76EE\u5F55\u5931\u8D25: ${outputDir}`, error);
|
|
557
|
-
}
|
|
558
|
-
}
|
|
559
|
-
function getAvailableStrategies(options) {
|
|
560
|
-
const { entry = "src/pages/*/main.{ts,js}", exclude = [], pageConfigs = {} } = options;
|
|
561
|
-
const log = createLogger(false);
|
|
562
|
-
const strategySet = /* @__PURE__ */ new Set();
|
|
563
|
-
const allFiles = glob2.sync(entry, { cwd: process.cwd() });
|
|
564
|
-
const entryFiles = filterEntryFiles(allFiles, entry, exclude, log);
|
|
565
|
-
if (entryFiles.length === 0) {
|
|
566
|
-
throw new Error(`\u672A\u627E\u5230\u5339\u914D\u7684\u5165\u53E3\u6587\u4EF6: ${entry}`);
|
|
567
|
-
}
|
|
568
|
-
try {
|
|
569
|
-
for (const entryFile of entryFiles) {
|
|
570
|
-
const pageContext = {
|
|
571
|
-
pageName: entryFile.name,
|
|
572
|
-
filePath: entryFile.file,
|
|
573
|
-
relativePath: path3.relative(process.cwd(), entryFile.file)
|
|
574
|
-
};
|
|
575
|
-
const pageConfig = getPageConfig(pageConfigs, pageContext, log);
|
|
576
|
-
const strategyName = (pageConfig == null ? void 0 : pageConfig.strategy) || "default";
|
|
577
|
-
strategySet.add(strategyName);
|
|
578
|
-
}
|
|
579
|
-
return Array.from(strategySet).sort();
|
|
580
|
-
} catch (error) {
|
|
581
|
-
log("\u83B7\u53D6\u53EF\u7528\u7B56\u7565\u5931\u8D25:", error);
|
|
582
|
-
return ["default"];
|
|
583
|
-
}
|
|
584
|
-
}
|
|
101
|
+
`}}import{mergeConfig as Z}from"vite";import{glob as H}from"glob";import*as h from"node:path";import*as b from"node:fs";function V(t){var c;let{entry:e="src/pages/*/main.{ts,js}",exclude:s=[],template:i="index.html",placeholder:n="<!--VITE_MULTI_PAGE_ENTRY-->",strategies:a={},pageConfigs:g={},forceBuildStrategy:l}=t,r=M(!0),o={};try{let f=H.sync(e,{cwd:process.cwd()}),p=T(f,e,s,r);if(p.length===0)return r("\u8B66\u544A: \u672A\u627E\u5230\u5339\u914D\u7684\u5165\u53E3\u6587\u4EF6"),{};let m=new Map,u=new Map;for(let d of p){let y={pageName:d.name,filePath:d.file,relativePath:h.relative(process.cwd(),d.file)},x=O(g,y,r),v=(x==null?void 0:x.strategy)||"default";m.set(d.name,v),u.has(v)||u.set(v,[]),(c=u.get(v))==null||c.push(d.name)}if(r(`\u{1F4C4} \u53D1\u73B0 ${p.length} \u4E2A\u9875\u9762: ${p.map(d=>d.name).join(", ")}`),l){let d=u.get(l)||[];if(d.length===0)return r(`\u8B66\u544A: \u7B56\u7565 "${l}" \u4E0B\u6CA1\u6709\u9875\u9762`),{};r(`\u5F3A\u5236\u6784\u5EFA\u7B56\u7565: ${l}, \u9875\u9762: ${d.join(", ")}`);let y=k(l,d,p,a[l],g,i,n,r);return o[l]=y,o}for(let[d,y]of u){if(y.length===0)continue;let x=a[d]||{},v=k(d,y,p,x,g,i,n,r);o[d]=v}if(Object.keys(o).length===0){r("\u8B66\u544A: \u672A\u751F\u6210\u4EFB\u4F55\u6784\u5EFA\u914D\u7F6E\uFF0C\u521B\u5EFA\u9ED8\u8BA4\u914D\u7F6E");let d=p.map(x=>x.name),y=k("default",d,p,{},g,i,n,r);o.default=y}let U=Object.keys(o);return r(`\u{1F4E6} \u6784\u5EFA\u7B56\u7565: ${U.join(", ")}`),o}catch(f){throw r("\u751F\u6210\u6784\u5EFA\u914D\u7F6E\u5931\u8D25:",f),f}}function k(t,e,s,i,n,a,g,l){let r={},o=[],c={};for(let m of e){let u=s.find(A=>A.name===m);if(!u)continue;let U={pageName:m,filePath:u.file,relativePath:h.relative(process.cwd(),u.file),strategy:t},d=O(n,U,l);d!=null&&d.define&&Object.assign(c,d.define);let y=a,x=`${m}.html`;b.existsSync(h.resolve(process.cwd(),x))?y=x:d!=null&&d.template&&(y=d.template);let v=h.resolve(process.cwd(),y);if(!b.existsSync(v)){l(`\u8B66\u544A: \u6A21\u677F\u6587\u4EF6\u4E0D\u5B58\u5728: ${y}`);continue}let j=b.readFileSync(v,"utf-8");if(j.includes(g)){let A=`./${u.file}`;j=j.replace(new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),A)}let L=h.resolve(process.cwd(),`.temp.mp.${m}.html`);b.writeFileSync(L,j),o.push(L),r[m]=L}let f={build:{rollupOptions:{input:r,output:{entryFileNames:"assets/[name]-[hash].js",chunkFileNames:"assets/[name]-[hash].js",assetFileNames:"assets/[name]-[hash][extname]"}},emptyOutDir:!1},define:{}},p=f;return i&&(p=Z(f,i)),Object.keys(c).length>0&&(p.define={...p.define,...c}),p.build||(p.build={}),p.build.rollupOptions||(p.build.rollupOptions={}),p.build.rollupOptions.input=r,p.build.emptyOutDir=!1,l(`\u7B56\u7565 "${t}" - ${e.length} \u4E2A\u9875\u9762`),p}function z(t=[]){let e=t.findIndex(i=>i==="--outDir");if(e!==-1&&e+1<t.length){let i=t[e+1];return h.resolve(process.cwd(),i)}let s=t.find(i=>i.startsWith("--outDir="));if(s){let i=s.split("=")[1];return h.resolve(process.cwd(),i)}return h.resolve(process.cwd(),"dist")}function ee(t=[]){let e=z(t),s=M(!0);try{b.existsSync(e)&&(b.rmSync(e,{recursive:!0,force:!0}),s(`\u{1F9F9} \u6E05\u7406\u8F93\u51FA\u76EE\u5F55: ${h.relative(process.cwd(),e)}`))}catch(i){s(`\u26A0\uFE0F \u6E05\u7406\u8F93\u51FA\u76EE\u5F55\u5931\u8D25: ${e}`,i)}}function te(t){let{entry:e="src/pages/*/main.{ts,js}",exclude:s=[],pageConfigs:i={}}=t,n=M(!1),a=new Set,g=H.sync(e,{cwd:process.cwd()}),l=T(g,e,s,n);if(l.length===0)throw new Error(`\u672A\u627E\u5230\u5339\u914D\u7684\u5165\u53E3\u6587\u4EF6: ${e}`);try{for(let r of l){let o={pageName:r.name,filePath:r.file,relativePath:h.relative(process.cwd(),r.file)},c=O(i,o,n),f=(c==null?void 0:c.strategy)||"default";a.add(f)}return Array.from(a).sort()}catch(r){return n("\u83B7\u53D6\u53EF\u7528\u7B56\u7565\u5931\u8D25:",r),["default"]}}import*as F from"node:fs";import*as E from"node:path";import{pathToFileURL as ne}from"node:url";import{Module as R}from"node:module";var q=["multipage.config.js","multipage.config.mjs","multipage.config.ts"];function B(){for(let t of q){let e=E.resolve(process.cwd(),t);if(F.existsSync(e))return!0}return!1}async function G(t){let e=await ie();if(e){let s=e(t);return s||{}}return null}async function re(t){if(t.endsWith(".ts"))try{let e=await F.promises.readFile(t,"utf-8"),i=await(await import("esbuild")).transform(e,{loader:"ts",format:"cjs",target:"node16",sourcemap:!1}),n=new R(t);return n.filename=t,n.paths=R._nodeModulePaths(E.dirname(t)),n._compile(i.code,t),n.exports}catch(e){console.warn("esbuild \u8F6C\u8BD1\u5931\u8D25\uFF0C\u5C1D\u8BD5\u7B80\u5355\u8F6C\u6362:",e);let i=(await F.promises.readFile(t,"utf-8")).replace(/export\s+default\s+/,"module.exports = ").replace(/import\s+.*?from\s+['"][^'"]*['"];?\s*/g,"").replace(/:\s*[^=,})\]]+/g,""),n=new R(t);return n.filename=t,n.paths=R._nodeModulePaths(E.dirname(t)),n._compile(i,t),n.exports}if(t.endsWith(".js")||t.endsWith(".mjs"))return import(`${ne(t).href}?t=${Date.now()}`);throw new Error(`\u4E0D\u652F\u6301\u7684\u914D\u7F6E\u6587\u4EF6\u7C7B\u578B: ${t}`)}async function ie(){let t=process.cwd();for(let e of q){let s=E.resolve(t,e);if(F.existsSync(s))try{let i=await re(s),n=i.default||i;if(typeof n=="function")return n;console.warn(`\u914D\u7F6E\u6587\u4EF6 ${e} \u5FC5\u987B\u9ED8\u8BA4\u5BFC\u51FA\u4E00\u4E2A\u51FD\u6570`)}catch(i){e.endsWith(".ts")?(console.error(`\u52A0\u8F7DTypeScript\u914D\u7F6E\u6587\u4EF6 ${e} \u5931\u8D25:`,i),console.log("\u63D0\u793A\uFF1A\u786E\u4FDD\u4F60\u7684\u9879\u76EE\u652F\u6301TypeScript\uFF0C\u6216\u8005\u4F7F\u7528 .js/.mjs \u914D\u7F6E\u6587\u4EF6")):console.error(`\u52A0\u8F7D\u914D\u7F6E\u6587\u4EF6 ${e} \u5931\u8D25:`,i)}}return null}var $={entry:"src/pages/**/*.{ts,js}",exclude:[],template:"index.html",placeholder:"{{ENTRY_FILE}}",debug:!1,strategies:{default:{}},pageConfigs:{}};function D(t){return t?{entry:t.entry??$.entry,exclude:t.exclude??$.exclude,template:t.template??$.template,placeholder:t.placeholder??$.placeholder,debug:t.debug??$.debug,strategies:t.strategies??$.strategies,pageConfigs:t.pageConfigs??$.pageConfigs,__forceBuildStrategy:t.__forceBuildStrategy}:{...$}}function se(t){return typeof t=="function"?t:()=>t}function oe(t){return t}function le(t){let e,s=[],i=()=>{};return{name:"vite-multi-page",async configResolved(n){let a=null;B()&&(a=await G({mode:n.command==="serve"?"development":"production",command:n.command,isCLI:!1}));let g=D(a);e=t?t(g,{mode:n.command==="serve"?"development":"production",command:n.command,isCLI:!1}):g,i=e.debug??!1?console.log.bind(console,"[vite-multi-page]"):()=>{},i("Vite\u914D\u7F6E\u5DF2\u89E3\u6790, \u4F7F\u7528\u914D\u7F6E:",{strategies:Object.keys(e.strategies||{}),entry:e.entry})},async config(n,{command:a}){var g;if(a==="serve"){let l=process.argv,r=l.find(o=>o.startsWith("--strategy="));if(r){let o=r.split("=")[1];o&&(process.env.VITE_MULTI_PAGE_STRATEGY=o)}else{let o=l.findIndex(c=>c==="--strategy");if(o!==-1&&o+1<l.length){let c=l[o+1];process.env.VITE_MULTI_PAGE_STRATEGY=c}}process.env.VITE_MULTI_PAGE_STRATEGY||(process.env.VITE_MULTI_PAGE_STRATEGY="default")}if(a==="build"){if(!e){let c=null;B()&&(c=await G({mode:"production",command:"build",isCLI:!1}));let f=D(c);e=t?t(f,{mode:"production",command:"build",isCLI:!1}):f,i=e.debug??!1?console.log.bind(console,"[vite-multi-page]"):()=>{}}i("\u914D\u7F6E\u6784\u5EFA\u6A21\u5F0F");let l=process.env.VITE_MULTI_PAGE_STRATEGY,r=V({entry:e.entry||"src/pages/**/*.{ts,js}",exclude:e.exclude||[],template:e.template||"index.html",placeholder:e.placeholder||"{{ENTRY_FILE}}",strategies:e.strategies||{},pageConfigs:e.pageConfigs||{},forceBuildStrategy:l}),o=Object.keys(r)[0];if(o&&r[o]){i(`\u5E94\u7528\u6784\u5EFA\u7B56\u7565: ${o}`);let c=r[o],f=ae(n,c);Object.assign(n,f),i(`\u5DF2\u5E94\u7528\u7B56\u7565 "${o}" \u7684\u914D\u7F6E:`,{build:!!c.build,define:!!c.define,plugins:((g=c.plugins)==null?void 0:g.length)||0})}else throw i("\u672A\u627E\u5230\u53EF\u7528\u7684\u6784\u5EFA\u7B56\u7565\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u914D\u7F6E"),new Error(`\u274C \u6784\u5EFA\u5931\u8D25: \u672A\u627E\u5230\u4EFB\u4F55\u6784\u5EFA\u7B56\u7565
|
|
585
102
|
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
var CONFIG_FILES = [
|
|
592
|
-
"multipage.config.js",
|
|
593
|
-
"multipage.config.mjs",
|
|
594
|
-
"multipage.config.ts"
|
|
595
|
-
];
|
|
596
|
-
function hasCustomConfig() {
|
|
597
|
-
for (const filename of CONFIG_FILES) {
|
|
598
|
-
const configPath = path4.resolve(process.cwd(), filename);
|
|
599
|
-
if (fs3.existsSync(configPath)) {
|
|
600
|
-
return true;
|
|
601
|
-
}
|
|
602
|
-
}
|
|
603
|
-
return false;
|
|
604
|
-
}
|
|
605
|
-
async function loadUserConfig(context) {
|
|
606
|
-
const customConfig = await loadCustomConfig();
|
|
607
|
-
if (customConfig) {
|
|
608
|
-
const result = customConfig(context);
|
|
609
|
-
if (!result) {
|
|
610
|
-
return {};
|
|
611
|
-
}
|
|
612
|
-
return result;
|
|
613
|
-
}
|
|
614
|
-
return null;
|
|
615
|
-
}
|
|
616
|
-
async function loadConfigFile(filePath) {
|
|
617
|
-
if (filePath.endsWith(".ts")) {
|
|
618
|
-
try {
|
|
619
|
-
const code = await fs3.promises.readFile(filePath, "utf-8");
|
|
620
|
-
const esbuild = await import("esbuild");
|
|
621
|
-
const result = await esbuild.transform(code, {
|
|
622
|
-
loader: "ts",
|
|
623
|
-
format: "cjs",
|
|
624
|
-
// 使用 CommonJS 格式便于使用 Module._compile
|
|
625
|
-
target: "node16",
|
|
626
|
-
sourcemap: false
|
|
627
|
-
});
|
|
628
|
-
const tempModule = new Module(filePath);
|
|
629
|
-
tempModule.filename = filePath;
|
|
630
|
-
tempModule.paths = Module._nodeModulePaths(path4.dirname(filePath));
|
|
631
|
-
tempModule._compile(result.code, filePath);
|
|
632
|
-
return tempModule.exports;
|
|
633
|
-
} catch (esbuildError) {
|
|
634
|
-
console.warn("esbuild \u8F6C\u8BD1\u5931\u8D25\uFF0C\u5C1D\u8BD5\u7B80\u5355\u8F6C\u6362:", esbuildError);
|
|
635
|
-
const code = await fs3.promises.readFile(filePath, "utf-8");
|
|
636
|
-
const jsCode = code.replace(/export\s+default\s+/, "module.exports = ").replace(/import\s+.*?from\s+['"][^'"]*['"];?\s*/g, "").replace(/:\s*[^=,})\]]+/g, "");
|
|
637
|
-
const tempModule = new Module(filePath);
|
|
638
|
-
tempModule.filename = filePath;
|
|
639
|
-
tempModule.paths = Module._nodeModulePaths(path4.dirname(filePath));
|
|
640
|
-
tempModule._compile(jsCode, filePath);
|
|
641
|
-
return tempModule.exports;
|
|
642
|
-
}
|
|
643
|
-
}
|
|
644
|
-
if (filePath.endsWith(".js") || filePath.endsWith(".mjs")) {
|
|
645
|
-
const fileUrl = pathToFileURL(filePath).href;
|
|
646
|
-
return import(`${fileUrl}?t=${Date.now()}`);
|
|
647
|
-
}
|
|
648
|
-
throw new Error(`\u4E0D\u652F\u6301\u7684\u914D\u7F6E\u6587\u4EF6\u7C7B\u578B: ${filePath}`);
|
|
649
|
-
}
|
|
650
|
-
async function loadCustomConfig() {
|
|
651
|
-
const cwd = process.cwd();
|
|
652
|
-
for (const configFile of CONFIG_FILES) {
|
|
653
|
-
const configPath = path4.resolve(cwd, configFile);
|
|
654
|
-
if (fs3.existsSync(configPath)) {
|
|
655
|
-
try {
|
|
656
|
-
const configModule = await loadConfigFile(configPath);
|
|
657
|
-
const configFunction = configModule.default || configModule;
|
|
658
|
-
if (typeof configFunction === "function") {
|
|
659
|
-
return configFunction;
|
|
660
|
-
} else {
|
|
661
|
-
console.warn(`\u914D\u7F6E\u6587\u4EF6 ${configFile} \u5FC5\u987B\u9ED8\u8BA4\u5BFC\u51FA\u4E00\u4E2A\u51FD\u6570`);
|
|
662
|
-
}
|
|
663
|
-
} catch (error) {
|
|
664
|
-
if (configFile.endsWith(".ts")) {
|
|
665
|
-
console.error(`\u52A0\u8F7DTypeScript\u914D\u7F6E\u6587\u4EF6 ${configFile} \u5931\u8D25:`, error);
|
|
666
|
-
console.log("\u63D0\u793A\uFF1A\u786E\u4FDD\u4F60\u7684\u9879\u76EE\u652F\u6301TypeScript\uFF0C\u6216\u8005\u4F7F\u7528 .js/.mjs \u914D\u7F6E\u6587\u4EF6");
|
|
667
|
-
} else {
|
|
668
|
-
console.error(`\u52A0\u8F7D\u914D\u7F6E\u6587\u4EF6 ${configFile} \u5931\u8D25:`, error);
|
|
669
|
-
}
|
|
670
|
-
}
|
|
671
|
-
}
|
|
672
|
-
}
|
|
673
|
-
return null;
|
|
674
|
-
}
|
|
103
|
+
\u53EF\u80FD\u7684\u539F\u56E0\uFF1A
|
|
104
|
+
1. \u914D\u7F6E\u6587\u4EF6\u8FD4\u56DE\u7A7A\u5BF9\u8C61 {}
|
|
105
|
+
2. \u672A\u627E\u5230\u5339\u914D\u7684\u5165\u53E3\u6587\u4EF6
|
|
106
|
+
3. \u6A21\u677F\u6587\u4EF6\u4E0D\u5B58\u5728
|
|
107
|
+
4. \u672A\u914D\u7F6E strategies \u5BF9\u8C61
|
|
675
108
|
|
|
676
|
-
|
|
677
|
-
|
|
109
|
+
\u6700\u5C0F\u914D\u7F6E\u793A\u4F8B\uFF1A
|
|
110
|
+
export default () => ({
|
|
678
111
|
entry: "src/pages/**/*.{ts,js}",
|
|
679
|
-
exclude: [],
|
|
680
112
|
template: "index.html",
|
|
681
|
-
placeholder: "{{ENTRY_FILE}}",
|
|
682
|
-
debug: false,
|
|
683
113
|
strategies: {
|
|
684
114
|
default: {}
|
|
685
|
-
},
|
|
686
|
-
pageConfigs: {}
|
|
687
|
-
};
|
|
688
|
-
function mergeWithDefaults(userConfig) {
|
|
689
|
-
if (!userConfig) {
|
|
690
|
-
return { ...DEFAULT_CONFIG };
|
|
691
|
-
}
|
|
692
|
-
return {
|
|
693
|
-
entry: userConfig.entry ?? DEFAULT_CONFIG.entry,
|
|
694
|
-
exclude: userConfig.exclude ?? DEFAULT_CONFIG.exclude,
|
|
695
|
-
template: userConfig.template ?? DEFAULT_CONFIG.template,
|
|
696
|
-
placeholder: userConfig.placeholder ?? DEFAULT_CONFIG.placeholder,
|
|
697
|
-
debug: userConfig.debug ?? DEFAULT_CONFIG.debug,
|
|
698
|
-
strategies: userConfig.strategies ?? DEFAULT_CONFIG.strategies,
|
|
699
|
-
pageConfigs: userConfig.pageConfigs ?? DEFAULT_CONFIG.pageConfigs,
|
|
700
|
-
__forceBuildStrategy: userConfig.__forceBuildStrategy
|
|
701
|
-
};
|
|
702
|
-
}
|
|
703
|
-
|
|
704
|
-
// src/types.ts
|
|
705
|
-
function defineConfig(config) {
|
|
706
|
-
if (typeof config === "function") {
|
|
707
|
-
return config;
|
|
708
115
|
}
|
|
709
|
-
|
|
710
|
-
}
|
|
711
|
-
function defineConfigTransform(transform) {
|
|
712
|
-
return transform;
|
|
713
|
-
}
|
|
714
|
-
|
|
715
|
-
// src/index.ts
|
|
716
|
-
function viteMultiPage(transform) {
|
|
717
|
-
let resolvedOptions;
|
|
718
|
-
const tempFiles = [];
|
|
719
|
-
let log = () => {
|
|
720
|
-
};
|
|
721
|
-
return {
|
|
722
|
-
name: "vite-multi-page",
|
|
723
|
-
async configResolved(config) {
|
|
724
|
-
let userConfig = null;
|
|
725
|
-
if (hasCustomConfig()) {
|
|
726
|
-
userConfig = await loadUserConfig({
|
|
727
|
-
mode: config.command === "serve" ? "development" : "production",
|
|
728
|
-
command: config.command,
|
|
729
|
-
isCLI: false
|
|
730
|
-
});
|
|
731
|
-
}
|
|
732
|
-
const mergedConfig = mergeWithDefaults(userConfig);
|
|
733
|
-
resolvedOptions = transform ? transform(mergedConfig, {
|
|
734
|
-
mode: config.command === "serve" ? "development" : "production",
|
|
735
|
-
command: config.command,
|
|
736
|
-
isCLI: false
|
|
737
|
-
}) : mergedConfig;
|
|
738
|
-
const debug = resolvedOptions.debug ?? false;
|
|
739
|
-
log = debug ? console.log.bind(console, "[vite-multi-page]") : () => {
|
|
740
|
-
};
|
|
741
|
-
log("Vite\u914D\u7F6E\u5DF2\u89E3\u6790, \u4F7F\u7528\u914D\u7F6E:", {
|
|
742
|
-
strategies: Object.keys(resolvedOptions.strategies || {}),
|
|
743
|
-
entry: resolvedOptions.entry
|
|
744
|
-
});
|
|
745
|
-
},
|
|
746
|
-
async config(config, { command }) {
|
|
747
|
-
var _a;
|
|
748
|
-
if (command === "build") {
|
|
749
|
-
if (!resolvedOptions) {
|
|
750
|
-
let userConfig = null;
|
|
751
|
-
if (hasCustomConfig()) {
|
|
752
|
-
userConfig = await loadUserConfig({
|
|
753
|
-
mode: "production",
|
|
754
|
-
command: "build",
|
|
755
|
-
isCLI: false
|
|
756
|
-
});
|
|
757
|
-
}
|
|
758
|
-
const mergedConfig = mergeWithDefaults(userConfig);
|
|
759
|
-
resolvedOptions = transform ? transform(mergedConfig, {
|
|
760
|
-
mode: "production",
|
|
761
|
-
command: "build",
|
|
762
|
-
isCLI: false
|
|
763
|
-
}) : mergedConfig;
|
|
764
|
-
const debug = resolvedOptions.debug ?? false;
|
|
765
|
-
log = debug ? console.log.bind(console, "[vite-multi-page]") : () => {
|
|
766
|
-
};
|
|
767
|
-
}
|
|
768
|
-
log("\u914D\u7F6E\u6784\u5EFA\u6A21\u5F0F");
|
|
769
|
-
const forceBuildStrategy = process.env.VITE_BUILD_STRATEGY;
|
|
770
|
-
const buildConfigs = generateBuildConfig({
|
|
771
|
-
entry: resolvedOptions.entry || "src/pages/**/*.{ts,js}",
|
|
772
|
-
exclude: resolvedOptions.exclude || [],
|
|
773
|
-
template: resolvedOptions.template || "index.html",
|
|
774
|
-
placeholder: resolvedOptions.placeholder || "{{ENTRY_FILE}}",
|
|
775
|
-
strategies: resolvedOptions.strategies || {},
|
|
776
|
-
pageConfigs: resolvedOptions.pageConfigs || {},
|
|
777
|
-
forceBuildStrategy
|
|
778
|
-
});
|
|
779
|
-
const targetStrategy = Object.keys(buildConfigs)[0];
|
|
780
|
-
if (targetStrategy && buildConfigs[targetStrategy]) {
|
|
781
|
-
log(`\u5E94\u7528\u6784\u5EFA\u7B56\u7565: ${targetStrategy}`);
|
|
782
|
-
const strategyConfig = buildConfigs[targetStrategy];
|
|
783
|
-
const mergedConfig = mergeConfig2(config, strategyConfig);
|
|
784
|
-
Object.assign(config, mergedConfig);
|
|
785
|
-
log(`\u5DF2\u5E94\u7528\u7B56\u7565 "${targetStrategy}" \u7684\u914D\u7F6E:`, {
|
|
786
|
-
build: !!strategyConfig.build,
|
|
787
|
-
define: !!strategyConfig.define,
|
|
788
|
-
plugins: ((_a = strategyConfig.plugins) == null ? void 0 : _a.length) || 0
|
|
789
|
-
});
|
|
790
|
-
} else {
|
|
791
|
-
log("\u672A\u627E\u5230\u53EF\u7528\u7684\u6784\u5EFA\u7B56\u7565\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u914D\u7F6E");
|
|
792
|
-
throw new Error(
|
|
793
|
-
'\u274C \u6784\u5EFA\u5931\u8D25: \u672A\u627E\u5230\u4EFB\u4F55\u6784\u5EFA\u7B56\u7565\n\n\u53EF\u80FD\u7684\u539F\u56E0\uFF1A\n 1. \u914D\u7F6E\u6587\u4EF6\u8FD4\u56DE\u7A7A\u5BF9\u8C61 {}\n 2. \u672A\u627E\u5230\u5339\u914D\u7684\u5165\u53E3\u6587\u4EF6\n 3. \u6A21\u677F\u6587\u4EF6\u4E0D\u5B58\u5728\n 4. \u672A\u914D\u7F6E strategies \u5BF9\u8C61\n\n\u6700\u5C0F\u914D\u7F6E\u793A\u4F8B\uFF1A\nexport default () => ({\n entry: "src/pages/**/*.{ts,js}",\n template: "index.html",\n strategies: {\n default: {}\n }\n});'
|
|
794
|
-
);
|
|
795
|
-
}
|
|
796
|
-
}
|
|
797
|
-
},
|
|
798
|
-
configureServer(server) {
|
|
799
|
-
if (server.config.command === "serve") {
|
|
800
|
-
log("\u914D\u7F6E\u5F00\u53D1\u670D\u52A1\u5668");
|
|
801
|
-
setupDevMiddleware(
|
|
802
|
-
server,
|
|
803
|
-
{
|
|
804
|
-
entry: resolvedOptions.entry || "src/pages/**/*.{ts,js}",
|
|
805
|
-
exclude: resolvedOptions.exclude || [],
|
|
806
|
-
template: resolvedOptions.template || "index.html",
|
|
807
|
-
placeholder: resolvedOptions.placeholder || "{{ENTRY_FILE}}",
|
|
808
|
-
strategies: resolvedOptions.strategies || {},
|
|
809
|
-
pageConfigs: resolvedOptions.pageConfigs || {}
|
|
810
|
-
},
|
|
811
|
-
log
|
|
812
|
-
);
|
|
813
|
-
}
|
|
814
|
-
},
|
|
815
|
-
buildEnd() {
|
|
816
|
-
if (tempFiles.length > 0) {
|
|
817
|
-
log(`\u6E05\u7406 ${tempFiles.length} \u4E2A\u4E34\u65F6\u6587\u4EF6`);
|
|
818
|
-
tempFiles.forEach((file) => {
|
|
819
|
-
try {
|
|
820
|
-
if (fs4.existsSync(file)) {
|
|
821
|
-
fs4.unlinkSync(file);
|
|
822
|
-
log(`\u5220\u9664\u4E34\u65F6\u6587\u4EF6: ${file}`);
|
|
823
|
-
}
|
|
824
|
-
} catch (error) {
|
|
825
|
-
log(`\u5220\u9664\u4E34\u65F6\u6587\u4EF6\u5931\u8D25: ${file}`, error);
|
|
826
|
-
}
|
|
827
|
-
});
|
|
828
|
-
tempFiles.length = 0;
|
|
829
|
-
}
|
|
830
|
-
}
|
|
831
|
-
};
|
|
832
|
-
}
|
|
833
|
-
var src_default = viteMultiPage;
|
|
834
|
-
export {
|
|
835
|
-
cleanViteOutputDirectory,
|
|
836
|
-
src_default as default,
|
|
837
|
-
defineConfig,
|
|
838
|
-
defineConfigTransform,
|
|
839
|
-
generateBuildConfig,
|
|
840
|
-
getAvailableStrategies,
|
|
841
|
-
getViteOutputDirectory,
|
|
842
|
-
mergeWithDefaults,
|
|
843
|
-
viteMultiPage
|
|
844
|
-
};
|
|
116
|
+
});`)}},configureServer(n){if(n.config.command==="serve"){i("\u914D\u7F6E\u5F00\u53D1\u670D\u52A1\u5668");let a=process.env.VITE_MULTI_PAGE_STRATEGY||"default";i(`\u5F00\u53D1\u6A21\u5F0F\u7B56\u7565: ${a}`),W(n,{entry:e.entry||"src/pages/**/*.{ts,js}",exclude:e.exclude||[],template:e.template||"index.html",placeholder:e.placeholder||"{{ENTRY_FILE}}",strategies:e.strategies||{},pageConfigs:e.pageConfigs||{},devStrategy:a},i)}},buildEnd(){s.length>0&&(i(`\u6E05\u7406 ${s.length} \u4E2A\u4E34\u65F6\u6587\u4EF6`),s.forEach(n=>{try{N.existsSync(n)&&(N.unlinkSync(n),i(`\u5220\u9664\u4E34\u65F6\u6587\u4EF6: ${n}`))}catch(a){i(`\u5220\u9664\u4E34\u65F6\u6587\u4EF6\u5931\u8D25: ${n}`,a)}}),s.length=0)}}}var Ve=le;export{ee as cleanViteOutputDirectory,Ve as default,se as defineConfig,oe as defineConfigTransform,V as generateBuildConfig,te as getAvailableStrategies,z as getViteOutputDirectory,D as mergeWithDefaults,le as viteMultiPage};
|
|
845
117
|
//# sourceMappingURL=index.mjs.map
|