@fchc8/vite-plugin-multi-page 1.7.1 → 1.7.2

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/index.mjs CHANGED
@@ -1,261 +1,14 @@
1
- // src/index.ts
2
- import * as fs4 from "node:fs";
3
- import { mergeConfig as mergeConfig2 } from "vite";
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 L from"node:fs";import{mergeConfig as ae}from"vite";import*as S from"node:path";import*as T from"node:fs";import{glob as Q}from"glob";import*as b from"node:path";function M(t,e,o,r){let n=[],f=new Map,a=e.replace(/\/\*.*$/,"");(!a||a===e)&&(a=b.dirname(e.split("*")[0]));let s=[];for(let i of t){if(o.includes(i))continue;let p=b.relative(a,i).split(b.sep);if(p.length===1){let d=p[0],g=b.basename(d,b.extname(d));s.push({name:g,file:i,priority:1})}else if(p.length>=2){let d=b.basename(i,b.extname(i)),g=p[0];d==="main"&&s.push({name:g,file:i,priority:2})}}for(let i of s){let l=f.get(i.name);l?i.priority>l.priority&&f.set(i.name,{file:i.file,priority:i.priority}):f.set(i.name,{file:i.file,priority:i.priority})}for(let[i,{file:l}]of f.entries())n.push({name:i,file:l});return n}function Y(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function R(t){return(...e)=>{t&&console.log("[vite-plugin-multi-page]",...e)}}function _(t,e,o){if(!t)return null;if(typeof t=="function"){let r=t(e);return r}for(let[r,n]of Object.entries(t)){if(r===e.pageName)return o(`\u7CBE\u786E\u5339\u914D\u9875\u9762 ${e.pageName}:`,n),n;if(n.match&&(Array.isArray(n.match)?n.match:[n.match]).some(s=>I(s,e.pageName)||I(s,e.relativePath)||I(s,e.filePath)))return o(`\u6A21\u5F0F\u5339\u914D\u9875\u9762 ${e.pageName} (\u6A21\u5F0F: ${n.match}):`,n),{...n,match:void 0};if(I(r,e.pageName))return o(`Glob\u5339\u914D\u9875\u9762 ${e.pageName} (\u6A21\u5F0F: ${r}):`,n),n}return null}function I(t,e){let o=t.replace(/\*\*/g,"__DOUBLE_STAR__").replace(/\*/g,"[^/]*").replace(/__DOUBLE_STAR__/g,".*");return new RegExp(`^${o}$`).test(e)}function K(t,e,o){try{let r=Q.sync(e.entry,{cwd:process.cwd()}),n=M(r,e.entry,e.exclude,o);if(n.length===0){o("\u8B66\u544A: \u672A\u627E\u5230\u5339\u914D\u7684\u5165\u53E3\u6587\u4EF6");return}let f=t.config.__cliStrategy||t.config.strategy;f&&(o(`\u5F00\u53D1\u670D\u52A1\u5668\u4F7F\u7528\u6307\u5B9A\u7684\u7B56\u7565: ${f}`),n=n.filter(a=>{var l;let s=a.name,i=((l=e.appliedStrategies)==null?void 0:l.get(s))||void 0;return f==="default"?!i||i==="default":i===f}),o(`\u7B56\u7565 "${f}" \u4E0B\u53EF\u7528\u7684\u9875\u9762: ${n.map(a=>a.name).join(", ")||"\u65E0"}`)),o("\u5F00\u53D1\u670D\u52A1\u5668\u5E94\u7528\u7684\u5165\u53E3\u6587\u4EF6:",n),t.middlewares.use(async(a,s,i)=>{var l;try{let d=(a.url||"").split("?")[0];if(d==="/"){let u=X(n,e,o);s.statusCode=200,s.setHeader("Content-Type","text/html"),s.end(u);return}if(d.match(/\.(js|css|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot)$/)&&!d.endsWith(".html"))return i();let g="";if(d.endsWith(".html")?g=S.basename(d,".html"):d.startsWith("/")&&(g=d.substring(1)),!g)return i();let x=n.find(u=>u.name===g);if(!x)return i();let C={pageName:x.name,filePath:x.file,relativePath:S.relative(process.cwd(),x.file),strategy:void 0,isMatched:!1},y=_(e.pageConfigs,C,o);if(y!=null&&y.strategy)C.strategy=y.strategy;else if((l=e.appliedStrategies)!=null&&l.has(g)){let u=e.appliedStrategies.get(g);u&&(C.strategy=u)}let c="",h=S.resolve(process.cwd(),`${g}.html`);if(T.existsSync(h)?c=h:y!=null&&y.template?c=S.resolve(process.cwd(),y.template):c=S.resolve(process.cwd(),e.template),!T.existsSync(c))return i();let m=T.readFileSync(c,"utf-8");if(m.includes(e.placeholder)){let u=m;if(m=m.split(e.placeholder).join(`/${x.file}`),m===u){let E=Y(e.placeholder),F=new RegExp(E,"g");m=u.replace(F,`/${x.file}`),m===u&&(m=u.replace(/\{\{ENTRY_FILE\}\}/g,`/${x.file}`))}}if(y!=null&&y.define){let u=Object.entries(y.define).map(([E,F])=>{let J=typeof F=="string"?`"${F}"`:JSON.stringify(F);return`window.${E} = ${J};`}).join(`
2
+ `);u&&(m=m.replace(/<\/head>/i,`<script type="text/javascript">
3
+ ${u}
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>`))}s.statusCode=200,s.setHeader("Content-Type","text/html"),s.end(m)}catch(p){o(`\u5F00\u53D1\u670D\u52A1\u5668\u5904\u7406\u8BF7\u6C42\u5931\u8D25: ${p}`),i(p)}}),o("\u5F00\u53D1\u670D\u52A1\u5668\u914D\u7F6E\u5B8C\u6210")}catch(r){throw o(`\u914D\u7F6E\u5F00\u53D1\u670D\u52A1\u5668\u5931\u8D25: ${r}`),r}}var H=K;function X(t,e,o){try{let r=t.map(n=>{var l;let f={pageName:n.name,filePath:n.file,relativePath:S.relative(process.cwd(),n.file),strategy:void 0,isMatched:!1},a=_(e.pageConfigs,f,o),s="default";if(a!=null&&a.strategy)s=a.strategy;else if((l=e.appliedStrategies)!=null&&l.has(n.name)){let p=e.appliedStrategies.get(n.name);p&&(s=p)}let i=s!=="default"?`<span class="badge">${s}</span>`:"";return`
251
6
  <div class="page-item">
252
- <a href="${file.name}.html" class="page-link">
253
- ${file.name}${strategyBadge}
7
+ <a href="${n.name}.html" class="page-link">
8
+ ${n.name}${i}
254
9
  </a>
255
- <div class="page-path">${file.file}</div>
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 ${entryFiles.length} \u4E2A\u9875\u9762
83
+ \u627E\u5230 ${t.length} \u4E2A\u9875\u9762
331
84
  </div>
332
85
  <div class="page-list">
333
- ${pageItems}
86
+ ${r}
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(r){return o(`\u751F\u6210\u7D22\u5F15\u9875\u5931\u8D25: ${r}`),`
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>${error}</p>
98
+ <p>${r}</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 z}from"glob";import*as v from"node:path";import*as w from"node:fs";function V(t){var p;let{entry:e="src/pages/*/main.{ts,js}",exclude:o=[],template:r="index.html",placeholder:n="<!--VITE_MULTI_PAGE_ENTRY-->",strategies:f={},pageConfigs:a={},forceBuildStrategy:s}=t,i=R(!0),l={};try{let d=z.sync(e,{cwd:process.cwd()}),g=M(d,e,o,i);if(g.length===0)return i("\u8B66\u544A: \u672A\u627E\u5230\u5339\u914D\u7684\u5165\u53E3\u6587\u4EF6"),{};let x=new Map,C=new Map;for(let c of g){let h={pageName:c.name,filePath:c.file,relativePath:v.relative(process.cwd(),c.file)},m=_(a,h,i),P=(m==null?void 0:m.strategy)||"default";x.set(c.name,P),C.has(P)||C.set(P,[]),(p=C.get(P))==null||p.push(c.name)}if(i(`\u{1F4C4} \u53D1\u73B0 ${g.length} \u4E2A\u9875\u9762: ${g.map(c=>c.name).join(", ")}`),s){let c=C.get(s)||[];if(c.length===0)return i(`\u8B66\u544A: \u7B56\u7565 "${s}" \u4E0B\u6CA1\u6709\u9875\u9762`),{};i(`\u5F3A\u5236\u6784\u5EFA\u7B56\u7565: ${s}, \u9875\u9762: ${c.join(", ")}`);let h=B(s,c,g,f[s],a,r,n,i);return l[s]=h,l}for(let[c,h]of C){if(h.length===0)continue;let m=f[c]||{},P=B(c,h,g,m,a,r,n,i);l[c]=P}if(Object.keys(l).length===0){i("\u8B66\u544A: \u672A\u751F\u6210\u4EFB\u4F55\u6784\u5EFA\u914D\u7F6E\uFF0C\u521B\u5EFA\u9ED8\u8BA4\u914D\u7F6E");let c=g.map(m=>m.name),h=B("default",c,g,{},a,r,n,i);l.default=h}let y=Object.keys(l);return i(`\u{1F4E6} \u6784\u5EFA\u7B56\u7565: ${y.join(", ")}`),l}catch(d){throw i("\u751F\u6210\u6784\u5EFA\u914D\u7F6E\u5931\u8D25:",d),d}}function B(t,e,o,r,n,f,a,s){let i={},l=[],p={};for(let x of e){let C=o.find(F=>F.name===x);if(!C)continue;let y={pageName:x,filePath:C.file,relativePath:v.relative(process.cwd(),C.file),strategy:t},c=_(n,y,s);c!=null&&c.define&&Object.assign(p,c.define);let h=f,m=`${x}.html`;w.existsSync(v.resolve(process.cwd(),m))?h=m:c!=null&&c.template&&(h=c.template);let P=v.resolve(process.cwd(),h);if(!w.existsSync(P)){s(`\u8B66\u544A: \u6A21\u677F\u6587\u4EF6\u4E0D\u5B58\u5728: ${h}`);continue}let u=w.readFileSync(P,"utf-8");if(u.includes(a)){let F=`./${C.file}`;u=u.replace(new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),F)}let E=v.resolve(process.cwd(),`.temp.mp.${x}.html`);w.writeFileSync(E,u),l.push(E),i[x]=E}let d={build:{rollupOptions:{input:i,output:{entryFileNames:"assets/[name]-[hash].js",chunkFileNames:"assets/[name]-[hash].js",assetFileNames:"assets/[name]-[hash][extname]"}},emptyOutDir:!1},define:{}},g=d;return r&&(g=Z(d,r)),Object.keys(p).length>0&&(g.define={...g.define,...p}),g.build||(g.build={}),g.build.rollupOptions||(g.build.rollupOptions={}),g.build.rollupOptions.input=i,g.build.emptyOutDir=!1,s(`\u7B56\u7565 "${t}" - ${e.length} \u4E2A\u9875\u9762`),g}function G(t=[]){let e=t.findIndex(r=>r==="--outDir");if(e!==-1&&e+1<t.length){let r=t[e+1];return v.resolve(process.cwd(),r)}let o=t.find(r=>r.startsWith("--outDir="));if(o){let r=o.split("=")[1];return v.resolve(process.cwd(),r)}return v.resolve(process.cwd(),"dist")}function ee(t=[]){let e=G(t),o=R(!0);try{w.existsSync(e)&&(w.rmSync(e,{recursive:!0,force:!0}),o(`\u{1F9F9} \u6E05\u7406\u8F93\u51FA\u76EE\u5F55: ${v.relative(process.cwd(),e)}`))}catch(r){o(`\u26A0\uFE0F \u6E05\u7406\u8F93\u51FA\u76EE\u5F55\u5931\u8D25: ${e}`,r)}}function te(t){let{entry:e="src/pages/*/main.{ts,js}",exclude:o=[],pageConfigs:r={}}=t,n=R(!1),f=new Set,a=z.sync(e,{cwd:process.cwd()}),s=M(a,e,o,n);if(s.length===0)throw new Error(`\u672A\u627E\u5230\u5339\u914D\u7684\u5165\u53E3\u6587\u4EF6: ${e}`);try{for(let i of s){let l={pageName:i.name,filePath:i.file,relativePath:v.relative(process.cwd(),i.file)},p=_(r,l,n),d=(p==null?void 0:p.strategy)||"default";f.add(d)}return Array.from(f).sort()}catch(i){return n("\u83B7\u53D6\u53EF\u7528\u7B56\u7565\u5931\u8D25:",i),["default"]}}import*as D from"node:fs";import*as N from"node:path";import{pathToFileURL as ne}from"node:url";import{Module as U}from"node:module";var q=["multipage.config.js","multipage.config.mjs","multipage.config.ts"];function W(){for(let t of q){let e=N.resolve(process.cwd(),t);if(D.existsSync(e))return!0}return!1}async function A(t){let e=await ie();if(e){let o=e(t);return o||{}}return null}async function re(t){if(t.endsWith(".ts"))try{let e=await D.promises.readFile(t,"utf-8"),r=await(await import("esbuild")).transform(e,{loader:"ts",format:"cjs",target:"node16",sourcemap:!1}),n=new U(t);return n.filename=t,n.paths=U._nodeModulePaths(N.dirname(t)),n._compile(r.code,t),n.exports}catch(e){console.warn("esbuild \u8F6C\u8BD1\u5931\u8D25\uFF0C\u5C1D\u8BD5\u7B80\u5355\u8F6C\u6362:",e);let r=(await D.promises.readFile(t,"utf-8")).replace(/export\s+default\s+/,"module.exports = ").replace(/import\s+.*?from\s+['"][^'"]*['"];?\s*/g,"").replace(/:\s*[^=,})\]]+/g,""),n=new U(t);return n.filename=t,n.paths=U._nodeModulePaths(N.dirname(t)),n._compile(r,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 o=N.resolve(t,e);if(D.existsSync(o))try{let r=await re(o),n=r.default||r;if(typeof n=="function")return n;console.warn(`\u914D\u7F6E\u6587\u4EF6 ${e} \u5FC5\u987B\u9ED8\u8BA4\u5BFC\u51FA\u4E00\u4E2A\u51FD\u6570`)}catch(r){e.endsWith(".ts")?(console.error(`\u52A0\u8F7DTypeScript\u914D\u7F6E\u6587\u4EF6 ${e} \u5931\u8D25:`,r),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:`,r)}}return null}var j={entry:"src/pages/**/*.{ts,js}",exclude:[],template:"index.html",placeholder:"{{ENTRY_FILE}}",debug:!1,strategies:{default:{}},pageConfigs:{}};function k(t){return t?{entry:t.entry??j.entry,exclude:t.exclude??j.exclude,template:t.template??j.template,placeholder:t.placeholder??j.placeholder,debug:t.debug??j.debug,strategies:t.strategies??j.strategies,pageConfigs:t.pageConfigs??j.pageConfigs,__forceBuildStrategy:t.__forceBuildStrategy}:{...j}}function oe(t){return typeof t=="function"?t:()=>t}function se(t){return t}function le(t){let e,o=[],r=()=>{};return{name:"vite-multi-page",async configResolved(n){let f=null;W()&&(f=await A({mode:n.command==="serve"?"development":"production",command:n.command,isCLI:!1}));let a=k(f);e=t?t(a,{mode:n.command==="serve"?"development":"production",command:n.command,isCLI:!1}):a,r=e.debug??!1?console.log.bind(console,"[vite-multi-page]"):()=>{},r("Vite\u914D\u7F6E\u5DF2\u89E3\u6790, \u4F7F\u7528\u914D\u7F6E:",{strategies:Object.keys(e.strategies||{}),entry:e.entry})},async config(n,{command:f}){var a;if(f==="build"){if(!e){let p=null;W()&&(p=await A({mode:"production",command:"build",isCLI:!1}));let d=k(p);e=t?t(d,{mode:"production",command:"build",isCLI:!1}):d,r=e.debug??!1?console.log.bind(console,"[vite-multi-page]"):()=>{}}r("\u914D\u7F6E\u6784\u5EFA\u6A21\u5F0F");let s=process.env.VITE_BUILD_STRATEGY,i=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:s}),l=Object.keys(i)[0];if(l&&i[l]){r(`\u5E94\u7528\u6784\u5EFA\u7B56\u7565: ${l}`);let p=i[l],d=ae(n,p);Object.assign(n,d),r(`\u5DF2\u5E94\u7528\u7B56\u7565 "${l}" \u7684\u914D\u7F6E:`,{build:!!p.build,define:!!p.define,plugins:((a=p.plugins)==null?void 0:a.length)||0})}else throw r("\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
- // src/config-loader.ts
587
- import * as fs3 from "node:fs";
588
- import * as path4 from "node:path";
589
- import { pathToFileURL } from "node:url";
590
- import { Module } from "node:module";
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
- // src/defaults.ts
677
- var DEFAULT_CONFIG = {
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
- return () => config;
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){n.config.command==="serve"&&(r("\u914D\u7F6E\u5F00\u53D1\u670D\u52A1\u5668"),H(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||{}},r))},buildEnd(){o.length>0&&(r(`\u6E05\u7406 ${o.length} \u4E2A\u4E34\u65F6\u6587\u4EF6`),o.forEach(n=>{try{L.existsSync(n)&&(L.unlinkSync(n),r(`\u5220\u9664\u4E34\u65F6\u6587\u4EF6: ${n}`))}catch(f){r(`\u5220\u9664\u4E34\u65F6\u6587\u4EF6\u5931\u8D25: ${n}`,f)}}),o.length=0)}}}var Ve=le;export{ee as cleanViteOutputDirectory,Ve as default,oe as defineConfig,se as defineConfigTransform,V as generateBuildConfig,te as getAvailableStrategies,G as getViteOutputDirectory,k as mergeWithDefaults,le as viteMultiPage};
845
117
  //# sourceMappingURL=index.mjs.map