@fchc8/vite-plugin-multi-page 1.1.1 → 1.3.1

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.js CHANGED
@@ -1,4 +1,3 @@
1
- // @ts-nocheck
2
1
  "use strict";
3
2
  var __create = Object.create;
4
3
  var __defProp = Object.defineProperty;
@@ -32,24 +31,15 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
32
31
  var src_exports = {};
33
32
  __export(src_exports, {
34
33
  default: () => src_default,
34
+ defineConfig: () => defineConfig,
35
+ defineConfigTransform: () => defineConfigTransform,
36
+ generateBuildConfig: () => generateBuildConfig,
37
+ getAvailableStrategies: () => getAvailableStrategies,
35
38
  viteMultiPage: () => viteMultiPage
36
39
  });
37
40
  module.exports = __toCommonJS(src_exports);
38
- var path4 = __toESM(require("path"));
39
- var fs3 = __toESM(require("fs"));
40
- var import_glob3 = require("glob");
41
-
42
- // src/utils.ts
43
- function escapeRegExp(string) {
44
- return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
45
- }
46
- function createLogger(debug) {
47
- return (...args) => {
48
- if (debug) {
49
- console.log("[vite-plugin-multi-page]", ...args);
50
- }
51
- };
52
- }
41
+ var fs4 = __toESM(require("fs"));
42
+ var import_vite2 = require("vite");
53
43
 
54
44
  // src/dev-server.ts
55
45
  var path2 = __toESM(require("path"));
@@ -61,7 +51,10 @@ var path = __toESM(require("path"));
61
51
  function filterEntryFiles(files, entry, exclude, log) {
62
52
  const result = [];
63
53
  const nameToFile = /* @__PURE__ */ new Map();
64
- const basePattern = entry.replace(/\/\*\*.*$/, "");
54
+ let basePattern = entry.replace(/\/\*.*$/, "");
55
+ if (!basePattern || basePattern === entry) {
56
+ basePattern = path.dirname(entry.split("*")[0]);
57
+ }
65
58
  log("\u57FA\u7840\u76EE\u5F55\u6A21\u5F0F:", basePattern);
66
59
  const candidateFiles = [];
67
60
  for (const file of files) {
@@ -95,30 +88,38 @@ function filterEntryFiles(files, entry, exclude, log) {
95
88
  for (const candidate of candidateFiles) {
96
89
  const existing = nameToFile.get(candidate.name);
97
90
  if (!existing) {
98
- nameToFile.set(candidate.name, candidate.file);
91
+ nameToFile.set(candidate.name, { file: candidate.file, priority: candidate.priority });
99
92
  log(`\u2705 \u6DFB\u52A0\u9875\u9762: ${candidate.name} -> ${candidate.file}`);
100
93
  } else {
101
- const existingCandidate = candidateFiles.find((c) => c.file === existing);
102
- if (existingCandidate && candidate.priority > existingCandidate.priority) {
103
- nameToFile.set(candidate.name, candidate.file);
104
- log(`\u{1F504} \u66FF\u6362\u9875\u9762: ${candidate.name} -> ${candidate.file} (\u66FF\u6362 ${existing})`);
94
+ if (candidate.priority > existing.priority) {
95
+ nameToFile.set(candidate.name, { file: candidate.file, priority: candidate.priority });
96
+ log(
97
+ `\u{1F504} \u66FF\u6362\u9875\u9762: ${candidate.name} -> ${candidate.file} (\u66FF\u6362 ${existing.file}, \u76EE\u5F55\u4F18\u5148)`
98
+ );
105
99
  } else {
106
- log(`\u26A0\uFE0F \u51B2\u7A81\u8DF3\u8FC7: ${candidate.name} -> ${candidate.file} (\u4FDD\u7559 ${existing})`);
100
+ log(`\u26A0\uFE0F \u51B2\u7A81\u8DF3\u8FC7: ${candidate.name} -> ${candidate.file} (\u4FDD\u7559 ${existing.file})`);
107
101
  }
108
102
  }
109
103
  }
110
- for (const [name, file] of nameToFile.entries()) {
104
+ for (const [name, { file }] of nameToFile.entries()) {
111
105
  result.push({ name, file });
112
106
  }
113
107
  return result;
114
108
  }
115
109
 
116
- // src/dev-server.ts
117
- function simpleMatch(pattern, text) {
118
- const regexPattern = pattern.replace(/\*\*/g, "__DOUBLE_STAR__").replace(/\*/g, "[^/]*").replace(/__DOUBLE_STAR__/g, ".*");
119
- const regex = new RegExp(`^${regexPattern}$`);
120
- return regex.test(text);
110
+ // src/utils.ts
111
+ function escapeRegExp(string) {
112
+ return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
113
+ }
114
+ function createLogger(debug) {
115
+ return (...args) => {
116
+ if (debug) {
117
+ console.log("[vite-plugin-multi-page]", ...args);
118
+ }
119
+ };
121
120
  }
121
+
122
+ // src/page-config.ts
122
123
  function getPageConfig(pageConfigs, context, log) {
123
124
  if (!pageConfigs)
124
125
  return null;
@@ -151,460 +152,684 @@ function getPageConfig(pageConfigs, context, log) {
151
152
  }
152
153
  return null;
153
154
  }
154
- function applyDevStrategy(server, strategy, log) {
155
- if (!strategy)
156
- return;
157
- log("\u5F00\u53D1\u6A21\u5F0F\u5E94\u7528\u6784\u5EFA\u7B56\u7565:", strategy);
158
- if (strategy.define) {
159
- log("\u5F00\u53D1\u73AF\u5883\u53D8\u91CF\u914D\u7F6E:", strategy.define);
160
- }
161
- if (strategy.alias) {
162
- log("\u5F00\u53D1\u522B\u540D\u914D\u7F6E:", strategy.alias);
163
- }
164
- if (strategy.server) {
165
- log("\u670D\u52A1\u5668\u914D\u7F6E:", strategy.server);
166
- }
167
- if (strategy.css) {
168
- log("CSS\u914D\u7F6E:", strategy.css);
169
- }
170
- if (strategy.optimizeDeps) {
171
- log("\u4F9D\u8D56\u4F18\u5316\u914D\u7F6E:", strategy.optimizeDeps);
172
- }
155
+ function simpleMatch(pattern, text) {
156
+ const regexPattern = pattern.replace(/\*\*/g, "__DOUBLE_STAR__").replace(/\*/g, "[^/]*").replace(/__DOUBLE_STAR__/g, ".*");
157
+ const regex = new RegExp(`^${regexPattern}$`);
158
+ return regex.test(text);
173
159
  }
160
+
161
+ // src/dev-server.ts
174
162
  function configureDevServer(server, options, log) {
175
- const allFiles = import_glob.glob.sync(options.entry, { cwd: process.cwd() });
176
- const entryFiles = filterEntryFiles(allFiles, options.entry, options.exclude, log);
177
- const pageMap = /* @__PURE__ */ new Map();
178
- entryFiles.forEach(({ name, file }) => {
179
- const pageConfig = getPageConfig(
180
- options.pageConfigs,
181
- {
182
- pageName: name,
183
- filePath: file,
184
- relativePath: path2.relative(process.cwd(), file),
185
- strategy: void 0,
186
- isMatched: false
187
- },
188
- log
189
- );
190
- const strategy = (pageConfig == null ? void 0 : pageConfig.strategy) || "default";
191
- pageMap.set(name, {
192
- file,
193
- config: pageConfig,
194
- strategy
195
- });
196
- if (options.buildStrategies && (pageConfig == null ? void 0 : pageConfig.strategy)) {
197
- const buildStrategy = options.buildStrategies[pageConfig.strategy];
198
- if (buildStrategy) {
199
- applyDevStrategy(server, buildStrategy, log);
200
- }
201
- }
202
- });
203
- const pageNames = Array.from(pageMap.keys());
204
- log("Available pages:", pageNames);
205
- log("Page mapping with configs:", Object.fromEntries(pageMap));
206
- server.middlewares.use((req, res, next) => {
207
- var _a;
208
- const originalUrl = req.url;
209
- const url = originalUrl == null ? void 0 : originalUrl.split("?")[0];
210
- if (!url) {
211
- return next();
163
+ try {
164
+ const allFiles = import_glob.glob.sync(options.entry, { cwd: process.cwd() });
165
+ let entryFiles = filterEntryFiles(allFiles, options.entry, options.exclude, log);
166
+ if (entryFiles.length === 0) {
167
+ log("\u8B66\u544A: \u672A\u627E\u5230\u5339\u914D\u7684\u5165\u53E3\u6587\u4EF6");
168
+ return;
212
169
  }
213
- log(`\u5904\u7406\u8BF7\u6C42: ${url}`);
214
- if (url === "/" && pageNames.length > 0) {
215
- const defaultPage = pageNames.includes("index") ? "index" : pageNames[0];
216
- log(`\u6839\u8DEF\u5F84\u91CD\u5B9A\u5411\u5230: ${defaultPage}`);
217
- req.url = `/${defaultPage}.html`;
170
+ const cliStrategy = server.config.__cliStrategy || server.config.strategy;
171
+ if (cliStrategy) {
172
+ log(`\u5F00\u53D1\u670D\u52A1\u5668\u4F7F\u7528\u6307\u5B9A\u7684\u7B56\u7565: ${cliStrategy}`);
173
+ entryFiles = entryFiles.filter((file) => {
174
+ var _a;
175
+ const pageName = file.name;
176
+ const pageStrategy = ((_a = options.appliedStrategies) == null ? void 0 : _a.get(pageName)) || void 0;
177
+ if (cliStrategy === "default") {
178
+ return !pageStrategy || pageStrategy === "default";
179
+ }
180
+ return pageStrategy === cliStrategy;
181
+ });
182
+ log(`\u7B56\u7565 "${cliStrategy}" \u4E0B\u53EF\u7528\u7684\u9875\u9762: ${entryFiles.map((f) => f.name).join(", ") || "\u65E0"}`);
218
183
  }
219
- const finalUrl = (_a = req.url) == null ? void 0 : _a.split("?")[0];
220
- const pageMatch = finalUrl == null ? void 0 : finalUrl.match(/^\/([^\/\.]+)(\.html)?$/);
221
- if (pageMatch) {
222
- const pageName = pageMatch[1];
223
- log(`\u5339\u914D\u5230\u9875\u9762: ${pageName}`);
224
- log(`\u53EF\u7528\u9875\u9762\u5217\u8868: ${pageNames.join(", ")}`);
225
- if (pageMap.has(pageName)) {
226
- const pageInfo = pageMap.get(pageName);
227
- if (!pageInfo) {
228
- log(`\u9875\u9762\u4FE1\u606F\u83B7\u53D6\u5931\u8D25: ${pageName}`);
184
+ log("\u5F00\u53D1\u670D\u52A1\u5668\u5E94\u7528\u7684\u5165\u53E3\u6587\u4EF6:", entryFiles);
185
+ server.middlewares.use(async (req, res, next) => {
186
+ var _a;
187
+ try {
188
+ const url = req.url || "";
189
+ const pathWithoutQuery = url.split("?")[0];
190
+ if (pathWithoutQuery === "/") {
191
+ const indexHtml = generateIndexHtml(entryFiles, options, log);
192
+ res.statusCode = 200;
193
+ res.setHeader("Content-Type", "text/html");
194
+ res.end(indexHtml);
195
+ return;
196
+ }
197
+ if (pathWithoutQuery.match(/\.(js|css|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot)$/) && !pathWithoutQuery.endsWith(".html")) {
229
198
  return next();
230
199
  }
231
- const relativeEntryPath = pageInfo.file;
232
- const pageConfig = pageInfo.config;
233
- const entryPath = path2.resolve(process.cwd(), relativeEntryPath);
234
- log(`\u9875\u9762 ${pageName} \u5BF9\u5E94\u6587\u4EF6: ${relativeEntryPath}`);
235
- log(`\u9875\u9762\u914D\u7F6E:`, pageConfig);
236
- if (fs.existsSync(entryPath)) {
237
- log(`\u627E\u5230\u5165\u53E3\u6587\u4EF6: ${entryPath}`);
238
- const templateFile = (pageConfig == null ? void 0 : pageConfig.template) || options.template;
239
- const templatePath = path2.resolve(process.cwd(), templateFile);
240
- if (fs.existsSync(templatePath)) {
241
- let html = fs.readFileSync(templatePath, "utf-8");
242
- log(`\u8BFB\u53D6\u6A21\u677F\u6587\u4EF6: ${templatePath}`);
243
- log(`\u6A21\u677F\u5185\u5BB9\u5305\u542B\u5360\u4F4D\u7B26: ${html.includes(options.placeholder)}`);
244
- if (!html.includes(options.placeholder)) {
245
- console.warn(
246
- `[vite-plugin-multi-page] \u6A21\u677F\u6587\u4EF6\u4E2D\u6CA1\u6709\u627E\u5230\u5360\u4F4D\u7B26: ${options.placeholder}`
247
- );
248
- return next();
249
- }
250
- const entryFile = `/${relativeEntryPath}`;
251
- html = html.replace(new RegExp(escapeRegExp(options.placeholder), "g"), entryFile);
252
- if (pageConfig == null ? void 0 : pageConfig.define) {
253
- const defineScript = Object.entries(pageConfig.define).map(([key, value]) => `window.${key} = ${JSON.stringify(value)};`).join("\n");
254
- if (defineScript) {
255
- const scriptTag = `<script>
256
- // \u9875\u9762\u7EA7\u73AF\u5883\u53D8\u91CF
257
- ${defineScript}
258
- </script>`;
259
- html = html.replace("</head>", `${scriptTag}
260
- </head>`);
261
- log(`\u6CE8\u5165\u9875\u9762\u73AF\u5883\u53D8\u91CF:`, pageConfig.define);
262
- }
263
- }
264
- log(`\u5360\u4F4D\u7B26 ${options.placeholder} \u66FF\u6362\u4E3A: ${entryFile}`);
265
- log(`\u4F7F\u7528\u6A21\u677F: ${templateFile}`);
266
- res.setHeader("Content-Type", "text/html");
267
- res.end(html);
268
- return;
269
- } else {
270
- log(`\u6A21\u677F\u6587\u4EF6\u4E0D\u5B58\u5728: ${templatePath}`);
200
+ let pageName = "";
201
+ if (pathWithoutQuery.endsWith(".html")) {
202
+ pageName = path2.basename(pathWithoutQuery, ".html");
203
+ } else if (pathWithoutQuery.startsWith("/")) {
204
+ pageName = pathWithoutQuery.substring(1);
205
+ }
206
+ if (!pageName) {
207
+ return next();
208
+ }
209
+ const matchedFile = entryFiles.find((file) => file.name === pageName);
210
+ if (!matchedFile) {
211
+ return next();
212
+ }
213
+ const pageContext = {
214
+ pageName: matchedFile.name,
215
+ filePath: matchedFile.file,
216
+ relativePath: path2.relative(process.cwd(), matchedFile.file),
217
+ strategy: void 0,
218
+ isMatched: false
219
+ };
220
+ const pageConfig = getPageConfig(options.pageConfigs, pageContext, log);
221
+ if (pageConfig == null ? void 0 : pageConfig.strategy) {
222
+ pageContext.strategy = pageConfig.strategy;
223
+ } else if ((_a = options.appliedStrategies) == null ? void 0 : _a.has(pageName)) {
224
+ const strategyName = options.appliedStrategies.get(pageName);
225
+ if (strategyName) {
226
+ pageContext.strategy = strategyName;
271
227
  }
228
+ }
229
+ let templatePath = "";
230
+ const pageSpecificTemplate = path2.resolve(process.cwd(), `${pageName}.html`);
231
+ if (fs.existsSync(pageSpecificTemplate)) {
232
+ templatePath = pageSpecificTemplate;
233
+ } else if (pageConfig == null ? void 0 : pageConfig.template) {
234
+ templatePath = path2.resolve(process.cwd(), pageConfig.template);
272
235
  } else {
273
- log(`\u5165\u53E3\u6587\u4EF6\u4E0D\u5B58\u5728: ${entryPath}`);
236
+ templatePath = path2.resolve(process.cwd(), options.template);
274
237
  }
275
- } else {
276
- log(`\u9875\u9762 ${pageName} \u4E0D\u5728\u53EF\u7528\u5217\u8868\u4E2D`);
238
+ if (!fs.existsSync(templatePath)) {
239
+ return next();
240
+ }
241
+ let html = fs.readFileSync(templatePath, "utf-8");
242
+ const containsPlaceholder = html.includes(options.placeholder);
243
+ if (containsPlaceholder) {
244
+ const originalHtml = html;
245
+ html = html.split(options.placeholder).join(`/${matchedFile.file}`);
246
+ if (html === originalHtml) {
247
+ const escapedPlaceholder = escapeRegExp(options.placeholder);
248
+ const placeholderRegex = new RegExp(escapedPlaceholder, "g");
249
+ html = originalHtml.replace(placeholderRegex, `/${matchedFile.file}`);
250
+ if (html === originalHtml) {
251
+ html = originalHtml.replace(/\{\{ENTRY_FILE\}\}/g, `/${matchedFile.file}`);
252
+ }
253
+ }
254
+ }
255
+ if (pageConfig == null ? void 0 : pageConfig.define) {
256
+ const defineScript = Object.entries(pageConfig.define).map(([key, value]) => {
257
+ const stringValue = typeof value === "string" ? `"${value}"` : JSON.stringify(value);
258
+ return `window.${key} = ${stringValue};`;
259
+ }).join("\n");
260
+ if (defineScript) {
261
+ html = html.replace(
262
+ /<\/head>/i,
263
+ `<script type="text/javascript">
264
+ ${defineScript}
265
+ </script>
266
+ </head>`
267
+ );
268
+ }
269
+ }
270
+ res.statusCode = 200;
271
+ res.setHeader("Content-Type", "text/html");
272
+ res.end(html);
273
+ } catch (error) {
274
+ log(`\u5F00\u53D1\u670D\u52A1\u5668\u5904\u7406\u8BF7\u6C42\u5931\u8D25: ${error}`);
275
+ next(error);
277
276
  }
278
- }
279
- next();
280
- });
277
+ });
278
+ log("\u5F00\u53D1\u670D\u52A1\u5668\u914D\u7F6E\u5B8C\u6210");
279
+ } catch (error) {
280
+ log(`\u914D\u7F6E\u5F00\u53D1\u670D\u52A1\u5668\u5931\u8D25: ${error}`);
281
+ throw error;
282
+ }
283
+ }
284
+ var setupDevMiddleware = configureDevServer;
285
+ function generateIndexHtml(entryFiles, options, log) {
286
+ try {
287
+ const pageItems = entryFiles.map((file) => {
288
+ var _a;
289
+ const pageContext = {
290
+ pageName: file.name,
291
+ filePath: file.file,
292
+ relativePath: path2.relative(process.cwd(), file.file),
293
+ strategy: void 0,
294
+ isMatched: false
295
+ };
296
+ const pageConfig = getPageConfig(options.pageConfigs, pageContext, log);
297
+ let strategy = "default";
298
+ if (pageConfig == null ? void 0 : pageConfig.strategy) {
299
+ strategy = pageConfig.strategy;
300
+ } else if ((_a = options.appliedStrategies) == null ? void 0 : _a.has(file.name)) {
301
+ const strategyName = options.appliedStrategies.get(file.name);
302
+ if (strategyName) {
303
+ strategy = strategyName;
304
+ }
305
+ }
306
+ const strategyBadge = strategy !== "default" ? `<span class="badge">${strategy}</span>` : "";
307
+ return `
308
+ <div class="page-item">
309
+ <a href="${file.name}.html" class="page-link">
310
+ ${file.name}${strategyBadge}
311
+ </a>
312
+ <div class="page-path">${file.file}</div>
313
+ </div>`;
314
+ }).join("");
315
+ return `
316
+ <!DOCTYPE html>
317
+ <html lang="en">
318
+ <head>
319
+ <meta charset="UTF-8">
320
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
321
+ <title>\u591A\u9875\u9762\u5E94\u7528\u7D22\u5F15</title>
322
+ <style>
323
+ body {
324
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
325
+ line-height: 1.6;
326
+ color: #333;
327
+ max-width: 1200px;
328
+ margin: 0 auto;
329
+ padding: 20px;
330
+ background-color: #f5f5f7;
331
+ }
332
+ h1 {
333
+ font-size: 24px;
334
+ margin-bottom: 20px;
335
+ color: #111;
336
+ }
337
+ .page-list {
338
+ display: grid;
339
+ grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
340
+ gap: 16px;
341
+ }
342
+ .page-item {
343
+ background-color: white;
344
+ border-radius: 8px;
345
+ padding: 16px;
346
+ box-shadow: 0 1px 3px rgba(0,0,0,0.1);
347
+ transition: transform 0.2s, box-shadow 0.2s;
348
+ }
349
+ .page-item:hover {
350
+ transform: translateY(-2px);
351
+ box-shadow: 0 4px 8px rgba(0,0,0,0.1);
352
+ }
353
+ .page-link {
354
+ display: flex;
355
+ align-items: center;
356
+ justify-content: space-between;
357
+ font-size: 18px;
358
+ font-weight: 500;
359
+ color: #0066cc;
360
+ text-decoration: none;
361
+ margin-bottom: 8px;
362
+ }
363
+ .page-path {
364
+ font-size: 14px;
365
+ color: #666;
366
+ word-break: break-all;
367
+ }
368
+ .badge {
369
+ display: inline-block;
370
+ font-size: 12px;
371
+ padding: 2px 8px;
372
+ border-radius: 12px;
373
+ background-color: #e6f2ff;
374
+ color: #0066cc;
375
+ margin-left: 8px;
376
+ }
377
+ .stats {
378
+ margin-bottom: 20px;
379
+ font-size: 14px;
380
+ color: #666;
381
+ }
382
+ </style>
383
+ </head>
384
+ <body>
385
+ <h1>\u591A\u9875\u9762\u5E94\u7528\u7D22\u5F15</h1>
386
+ <div class="stats">
387
+ \u627E\u5230 ${entryFiles.length} \u4E2A\u9875\u9762
388
+ </div>
389
+ <div class="page-list">
390
+ ${pageItems}
391
+ </div>
392
+ </body>
393
+ </html>
394
+ `;
395
+ } catch (error) {
396
+ log(`\u751F\u6210\u7D22\u5F15\u9875\u5931\u8D25: ${error}`);
397
+ return `
398
+ <!DOCTYPE html>
399
+ <html>
400
+ <head>
401
+ <title>\u9519\u8BEF</title>
402
+ </head>
403
+ <body>
404
+ <h1>\u751F\u6210\u7D22\u5F15\u9875\u65F6\u53D1\u751F\u9519\u8BEF</h1>
405
+ <p>${error}</p>
406
+ </body>
407
+ </html>
408
+ `;
409
+ }
281
410
  }
282
411
 
283
412
  // src/build-config.ts
413
+ var import_vite = require("vite");
414
+ var import_glob2 = require("glob");
284
415
  var path3 = __toESM(require("path"));
285
416
  var fs2 = __toESM(require("fs"));
286
- var import_glob2 = require("glob");
287
- function simpleMatch2(pattern, str) {
288
- const regexPattern = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
289
- const regex = new RegExp(`^${regexPattern}$`);
290
- return regex.test(str);
291
- }
292
- function createBuildConfig(config, options, log, tempFiles, pageMapping) {
293
- var _a, _b, _c;
294
- const allFiles = import_glob2.glob.sync(options.entry, { cwd: process.cwd() });
295
- const entryFiles = filterEntryFiles(allFiles, options.entry, options.exclude, log);
296
- if (entryFiles.length === 0) {
297
- console.warn("[vite-plugin-multi-page] No entry files found matching pattern:", options.entry);
298
- return;
299
- }
300
- log("\u626B\u63CF\u5230\u7684\u6240\u6709\u6587\u4EF6:", allFiles);
301
- log("\u8FC7\u6EE4\u540E\u7684\u5165\u53E3\u6587\u4EF6:", entryFiles);
302
- const existingTempFiles = import_glob2.glob.sync("temp-*.html", { cwd: process.cwd() });
303
- existingTempFiles.forEach((file) => {
304
- const fullPath = path3.resolve(process.cwd(), file);
305
- if (fs2.existsSync(fullPath)) {
306
- fs2.unlinkSync(fullPath);
307
- log(`\u6E05\u7406\u65E7\u7684\u4E34\u65F6\u6587\u4EF6: ${file}`);
417
+ function generateBuildConfig(options) {
418
+ var _a;
419
+ const {
420
+ entry = "src/pages/*/main.{ts,js}",
421
+ exclude = [],
422
+ template = "index.html",
423
+ placeholder = "<!--VITE_MULTI_PAGE_ENTRY-->",
424
+ strategies = {},
425
+ pageConfigs = {},
426
+ forceBuildStrategy
427
+ } = options;
428
+ const log = createLogger(true);
429
+ const buildConfigs = {};
430
+ try {
431
+ const allFiles = import_glob2.glob.sync(entry, { cwd: process.cwd() });
432
+ const entryFiles = filterEntryFiles(allFiles, entry, exclude, log);
433
+ if (entryFiles.length === 0) {
434
+ log("\u8B66\u544A: \u672A\u627E\u5230\u5339\u914D\u7684\u5165\u53E3\u6587\u4EF6");
435
+ return {};
308
436
  }
309
- });
310
- const input = {};
311
- tempFiles.length = 0;
312
- pageMapping.clear();
313
- const strategyGroups = {};
314
- const defaultStrategy = "default";
315
- entryFiles.forEach((entryFile) => {
316
- const { name, file } = entryFile;
317
- const pageConfig = getPageConfig2(
318
- options.pageConfigs,
319
- {
320
- pageName: name,
321
- filePath: file,
322
- relativePath: path3.relative(process.cwd(), file),
323
- strategy: void 0,
324
- isMatched: false
325
- },
326
- log
327
- );
328
- const strategy = (pageConfig == null ? void 0 : pageConfig.strategy) || defaultStrategy;
329
- if (!strategyGroups[strategy]) {
330
- strategyGroups[strategy] = [];
437
+ log(`\u53D1\u73B0 ${entryFiles.length} \u4E2A\u9875\u9762\u5165\u53E3`);
438
+ const pageStrategies = /* @__PURE__ */ new Map();
439
+ const strategyPages = /* @__PURE__ */ new Map();
440
+ for (const entryFile of entryFiles) {
441
+ const pageContext = {
442
+ pageName: entryFile.name,
443
+ filePath: entryFile.file,
444
+ relativePath: path3.relative(process.cwd(), entryFile.file)
445
+ };
446
+ const pageConfig = getPageConfig(pageConfigs, pageContext, log);
447
+ const strategyName = (pageConfig == null ? void 0 : pageConfig.strategy) || "default";
448
+ pageStrategies.set(entryFile.name, strategyName);
449
+ if (!strategyPages.has(strategyName)) {
450
+ strategyPages.set(strategyName, []);
451
+ }
452
+ (_a = strategyPages.get(strategyName)) == null ? void 0 : _a.push(entryFile.name);
331
453
  }
332
- strategyGroups[strategy].push(entryFile);
333
- const templatePath = (pageConfig == null ? void 0 : pageConfig.template) ? path3.resolve(process.cwd(), pageConfig.template) : path3.resolve(process.cwd(), options.template);
334
- const tempHtmlPath = path3.resolve(process.cwd(), `temp-${name}.html`);
335
- if (fs2.existsSync(templatePath)) {
336
- let html = fs2.readFileSync(templatePath, "utf-8");
337
- html = html.replace(new RegExp(escapeRegExp(options.placeholder), "g"), `/${file}`);
338
- fs2.writeFileSync(tempHtmlPath, html);
339
- tempFiles.push(tempHtmlPath);
340
- input[name] = tempHtmlPath;
341
- pageMapping.set(`temp-${name}.html`, `${name}.html`);
342
- log(`\u521B\u5EFA\u4E34\u65F6\u6587\u4EF6: temp-${name}.html -> ${name}.html (\u7B56\u7565: ${strategy})`);
454
+ log("\u9875\u9762\u7B56\u7565\u5206\u5E03:", Object.fromEntries(pageStrategies));
455
+ if (forceBuildStrategy) {
456
+ const targetPages = strategyPages.get(forceBuildStrategy) || [];
457
+ if (targetPages.length === 0) {
458
+ log(`\u8B66\u544A: \u7B56\u7565 "${forceBuildStrategy}" \u4E0B\u6CA1\u6709\u9875\u9762`);
459
+ return {};
460
+ }
461
+ log(`\u5F3A\u5236\u6784\u5EFA\u7B56\u7565: ${forceBuildStrategy}, \u9875\u9762: ${targetPages.join(", ")}`);
462
+ const config = generateStrategyConfig(
463
+ forceBuildStrategy,
464
+ targetPages,
465
+ entryFiles,
466
+ strategies[forceBuildStrategy],
467
+ pageConfigs,
468
+ template,
469
+ placeholder,
470
+ log
471
+ );
472
+ buildConfigs[forceBuildStrategy] = config;
473
+ return buildConfigs;
343
474
  }
344
- });
345
- log("Build input configuration:", input);
346
- log("Strategy groups:", Object.keys(strategyGroups));
347
- config.build = config.build || {};
348
- config.build.rollupOptions = config.build.rollupOptions || {};
349
- config.build.rollupOptions.input = input;
350
- const defaultStrategyConfig = (_a = options.buildStrategies) == null ? void 0 : _a[defaultStrategy];
351
- if (defaultStrategyConfig) {
352
- applyBuildStrategy(config, defaultStrategyConfig, log);
353
- }
354
- const strategyKeys = Object.keys(strategyGroups);
355
- if (strategyKeys.length === 1 && strategyKeys[0] !== defaultStrategy) {
356
- const singleStrategy = (_b = options.buildStrategies) == null ? void 0 : _b[strategyKeys[0]];
357
- if (singleStrategy) {
358
- applyBuildStrategy(config, singleStrategy, log);
475
+ for (const [strategyName, pages] of strategyPages) {
476
+ if (pages.length === 0)
477
+ continue;
478
+ log(`\u751F\u6210\u7B56\u7565 "${strategyName}" \u7684\u6784\u5EFA\u914D\u7F6E, \u9875\u9762: ${pages.join(", ")}`);
479
+ const strategyConfig = strategies[strategyName];
480
+ const config = generateStrategyConfig(
481
+ strategyName,
482
+ pages,
483
+ entryFiles,
484
+ strategyConfig,
485
+ pageConfigs,
486
+ template,
487
+ placeholder,
488
+ log
489
+ );
490
+ buildConfigs[strategyName] = config;
359
491
  }
360
- }
361
- if (strategyKeys.length > 1 || strategyKeys.length === 1 && strategyKeys[0] !== defaultStrategy && ((_c = options.buildStrategies) == null ? void 0 : _c[strategyKeys[0]])) {
362
- log("\u68C0\u6D4B\u5230\u591A\u6784\u5EFA\u7B56\u7565\uFF0C\u5C06\u521B\u5EFA\u7B56\u7565\u6620\u5C04");
363
- config.__multiPageStrategies = {
364
- groups: strategyGroups,
365
- strategies: options.buildStrategies,
366
- pageConfigs: options.pageConfigs
367
- };
492
+ log(`\u751F\u6210\u4E86 ${Object.keys(buildConfigs).length} \u4E2A\u6784\u5EFA\u914D\u7F6E`);
493
+ return buildConfigs;
494
+ } catch (error) {
495
+ log("\u751F\u6210\u6784\u5EFA\u914D\u7F6E\u5931\u8D25:", error);
496
+ throw error;
368
497
  }
369
498
  }
370
- function getPageConfig2(pageConfigs, context, log) {
371
- if (!pageConfigs)
372
- return null;
373
- if (typeof pageConfigs === "function") {
374
- const result = pageConfigs(context);
375
- if (result) {
376
- log(`\u51FD\u6570\u914D\u7F6E\u5339\u914D\u9875\u9762 ${context.pageName}:`, result);
499
+ function generateStrategyConfig(strategyName, pages, entryFiles, strategyConfig, pageConfigs, defaultTemplate, placeholder, log) {
500
+ const htmlInputs = {};
501
+ const tempFiles = [];
502
+ for (const pageName of pages) {
503
+ const entryFile = entryFiles.find((f) => f.name === pageName);
504
+ if (!entryFile)
505
+ continue;
506
+ const pageContext = {
507
+ pageName,
508
+ filePath: entryFile.file,
509
+ relativePath: path3.relative(process.cwd(), entryFile.file),
510
+ strategy: strategyName
511
+ };
512
+ const pageConfig = getPageConfig(pageConfigs, pageContext, log);
513
+ let templatePath = defaultTemplate;
514
+ const pageSpecificTemplate = `${pageName}.html`;
515
+ if (fs2.existsSync(path3.resolve(process.cwd(), pageSpecificTemplate))) {
516
+ templatePath = pageSpecificTemplate;
517
+ } else if (pageConfig == null ? void 0 : pageConfig.template) {
518
+ templatePath = pageConfig.template;
377
519
  }
378
- return result;
379
- }
380
- for (const [key, config] of Object.entries(pageConfigs)) {
381
- if (key === context.pageName) {
382
- log(`\u7CBE\u786E\u5339\u914D\u9875\u9762 ${context.pageName}:`, config);
383
- return config;
520
+ const templateFullPath = path3.resolve(process.cwd(), templatePath);
521
+ if (!fs2.existsSync(templateFullPath)) {
522
+ log(`\u8B66\u544A: \u6A21\u677F\u6587\u4EF6\u4E0D\u5B58\u5728: ${templatePath}`);
523
+ continue;
384
524
  }
385
- if (config.match) {
386
- const patterns = Array.isArray(config.match) ? config.match : [config.match];
387
- const isMatched = patterns.some(
388
- (pattern) => simpleMatch2(pattern, context.pageName) || simpleMatch2(pattern, context.relativePath) || simpleMatch2(pattern, context.filePath)
525
+ let templateContent = fs2.readFileSync(templateFullPath, "utf-8");
526
+ if (templateContent.includes(placeholder)) {
527
+ const entryPath = `./${entryFile.file}`;
528
+ templateContent = templateContent.replace(
529
+ new RegExp(placeholder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"),
530
+ entryPath
389
531
  );
390
- if (isMatched) {
391
- log(`\u6A21\u5F0F\u5339\u914D\u9875\u9762 ${context.pageName} (\u6A21\u5F0F: ${config.match}):`, config);
392
- return { ...config, match: void 0 };
393
- }
394
532
  }
395
- if (simpleMatch2(key, context.pageName)) {
396
- log(`Glob\u5339\u914D\u9875\u9762 ${context.pageName} (\u6A21\u5F0F: ${key}):`, config);
397
- return config;
533
+ if (pageConfig == null ? void 0 : pageConfig.define) {
534
+ const defineScript = Object.entries(pageConfig.define).map(([key, value]) => {
535
+ const stringValue = typeof value === "string" ? `"${value}"` : JSON.stringify(value);
536
+ return `window.${key} = ${stringValue};`;
537
+ }).join("\n");
538
+ if (defineScript) {
539
+ templateContent = templateContent.replace(
540
+ /<\/head>/i,
541
+ `<script type="text/javascript">
542
+ ${defineScript}
543
+ </script>
544
+ </head>`
545
+ );
546
+ }
398
547
  }
548
+ const tempHtmlPath = path3.resolve(process.cwd(), `.temp.mp.${pageName}.html`);
549
+ fs2.writeFileSync(tempHtmlPath, templateContent);
550
+ tempFiles.push(tempHtmlPath);
551
+ htmlInputs[pageName] = tempHtmlPath;
399
552
  }
400
- return null;
401
- }
402
- function applyBuildStrategy(config, strategy, log) {
403
- log("\u5E94\u7528\u6784\u5EFA\u7B56\u7565:", strategy);
404
- if (strategy.viteConfig) {
405
- const { build: viteBuild, ...otherViteConfig } = strategy.viteConfig;
406
- Object.keys(otherViteConfig).forEach((key) => {
407
- if (key !== "plugins") {
408
- const configKey = key;
409
- const viteConfigValue = otherViteConfig[key];
410
- if (viteConfigValue && typeof viteConfigValue === "object") {
411
- config[configKey] = {
412
- ...config[configKey] || {},
413
- ...viteConfigValue
414
- };
415
- } else {
416
- config[configKey] = viteConfigValue;
553
+ const baseConfig = {
554
+ build: {
555
+ rollupOptions: {
556
+ input: htmlInputs,
557
+ // 使用临时HTML文件作为输入
558
+ output: {
559
+ entryFileNames: "assets/[name]-[hash].js",
560
+ chunkFileNames: "assets/[name]-[hash].js",
561
+ assetFileNames: "assets/[name]-[hash][extname]"
417
562
  }
418
- }
419
- });
420
- if (viteBuild) {
421
- config.build = {
422
- ...config.build,
423
- ...viteBuild
563
+ },
564
+ outDir: `dist/${strategyName}`,
565
+ // 直接输出到策略目录
566
+ emptyOutDir: false
567
+ // 不清空输出目录,避免删除临时HTML文件
568
+ },
569
+ define: {}
570
+ };
571
+ let config = baseConfig;
572
+ if (strategyConfig) {
573
+ config = (0, import_vite.mergeConfig)(baseConfig, strategyConfig);
574
+ }
575
+ if (!config.build)
576
+ config.build = {};
577
+ if (!config.build.rollupOptions)
578
+ config.build.rollupOptions = {};
579
+ config.build.outDir = `dist/${strategyName}`;
580
+ config.build.rollupOptions.input = htmlInputs;
581
+ config.build.emptyOutDir = false;
582
+ log(`\u7B56\u7565 "${strategyName}" - ${pages.length} \u4E2A\u9875\u9762`);
583
+ return config;
584
+ }
585
+ function getAvailableStrategies(options) {
586
+ const { entry = "src/pages/*/main.{ts,js}", exclude = [], pageConfigs = {} } = options;
587
+ const log = createLogger(false);
588
+ const strategySet = /* @__PURE__ */ new Set();
589
+ try {
590
+ const allFiles = import_glob2.glob.sync(entry, { cwd: process.cwd() });
591
+ const entryFiles = filterEntryFiles(allFiles, entry, exclude, log);
592
+ for (const entryFile of entryFiles) {
593
+ const pageContext = {
594
+ pageName: entryFile.name,
595
+ filePath: entryFile.file,
596
+ relativePath: path3.relative(process.cwd(), entryFile.file)
424
597
  };
598
+ const pageConfig = getPageConfig(pageConfigs, pageContext, log);
599
+ const strategyName = (pageConfig == null ? void 0 : pageConfig.strategy) || "default";
600
+ strategySet.add(strategyName);
425
601
  }
602
+ return Array.from(strategySet).sort();
603
+ } catch (error) {
604
+ log("\u83B7\u53D6\u53EF\u7528\u7B56\u7565\u5931\u8D25:", error);
605
+ return ["default"];
426
606
  }
427
- if (strategy.output) {
428
- config.build.rollupOptions.output = {
429
- ...config.build.rollupOptions.output,
430
- ...strategy.output
431
- };
432
- }
433
- if (strategy.build) {
434
- config.build = {
435
- ...config.build,
436
- ...strategy.build
437
- };
438
- }
439
- if (strategy.define) {
440
- config.define = {
441
- ...config.define,
442
- ...strategy.define
443
- };
607
+ }
608
+
609
+ // src/config-loader.ts
610
+ var fs3 = __toESM(require("fs"));
611
+ var path4 = __toESM(require("path"));
612
+ var import_node_url = require("url");
613
+ var import_node_module = require("module");
614
+ var CONFIG_FILES = [
615
+ "multipage.config.js",
616
+ "multipage.config.mjs",
617
+ "multipage.config.ts"
618
+ ];
619
+ function hasCustomConfig() {
620
+ for (const filename of CONFIG_FILES) {
621
+ const configPath = path4.resolve(process.cwd(), filename);
622
+ if (fs3.existsSync(configPath)) {
623
+ return true;
624
+ }
444
625
  }
445
- if (strategy.alias) {
446
- config.resolve = config.resolve || {};
447
- config.resolve.alias = {
448
- ...config.resolve.alias,
449
- ...strategy.alias
450
- };
626
+ return false;
627
+ }
628
+ async function loadUserConfig(context) {
629
+ const customConfig = await loadCustomConfig();
630
+ if (customConfig) {
631
+ return customConfig(context);
451
632
  }
452
- if (strategy.server) {
453
- config.server = {
454
- ...config.server,
455
- ...strategy.server
456
- };
633
+ return null;
634
+ }
635
+ async function loadConfigFile(filePath) {
636
+ if (filePath.endsWith(".ts")) {
637
+ try {
638
+ const code = await fs3.promises.readFile(filePath, "utf-8");
639
+ const esbuild = await import("esbuild");
640
+ const result = await esbuild.transform(code, {
641
+ loader: "ts",
642
+ format: "cjs",
643
+ // 使用 CommonJS 格式便于使用 Module._compile
644
+ target: "node16",
645
+ sourcemap: false
646
+ });
647
+ const tempModule = new import_node_module.Module(filePath);
648
+ tempModule.filename = filePath;
649
+ tempModule.paths = import_node_module.Module._nodeModulePaths(path4.dirname(filePath));
650
+ tempModule._compile(result.code, filePath);
651
+ return tempModule.exports;
652
+ } catch (esbuildError) {
653
+ console.warn("esbuild \u8F6C\u8BD1\u5931\u8D25\uFF0C\u5C1D\u8BD5\u7B80\u5355\u8F6C\u6362:", esbuildError);
654
+ const code = await fs3.promises.readFile(filePath, "utf-8");
655
+ const jsCode = code.replace(/export\s+default\s+/, "module.exports = ").replace(/import\s+.*?from\s+['"][^'"]*['"];?\s*/g, "").replace(/:\s*[^=,})\]]+/g, "");
656
+ const tempModule = new import_node_module.Module(filePath);
657
+ tempModule.filename = filePath;
658
+ tempModule.paths = import_node_module.Module._nodeModulePaths(path4.dirname(filePath));
659
+ tempModule._compile(jsCode, filePath);
660
+ return tempModule.exports;
661
+ }
457
662
  }
458
- if (strategy.css) {
459
- config.css = {
460
- ...config.css,
461
- ...strategy.css
462
- };
663
+ if (filePath.endsWith(".js") || filePath.endsWith(".mjs")) {
664
+ const fileUrl = (0, import_node_url.pathToFileURL)(filePath).href;
665
+ return import(`${fileUrl}?t=${Date.now()}`);
463
666
  }
464
- if (strategy.optimizeDeps) {
465
- config.optimizeDeps = {
466
- ...config.optimizeDeps,
467
- ...strategy.optimizeDeps
468
- };
667
+ throw new Error(`\u4E0D\u652F\u6301\u7684\u914D\u7F6E\u6587\u4EF6\u7C7B\u578B: ${filePath}`);
668
+ }
669
+ async function loadCustomConfig() {
670
+ const cwd = process.cwd();
671
+ for (const configFile of CONFIG_FILES) {
672
+ const configPath = path4.resolve(cwd, configFile);
673
+ if (fs3.existsSync(configPath)) {
674
+ try {
675
+ const configModule = await loadConfigFile(configPath);
676
+ const configFunction = configModule.default || configModule;
677
+ if (typeof configFunction === "function") {
678
+ return configFunction;
679
+ } else {
680
+ console.warn(`\u914D\u7F6E\u6587\u4EF6 ${configFile} \u5FC5\u987B\u9ED8\u8BA4\u5BFC\u51FA\u4E00\u4E2A\u51FD\u6570`);
681
+ }
682
+ } catch (error) {
683
+ if (configFile.endsWith(".ts")) {
684
+ console.error(`\u52A0\u8F7DTypeScript\u914D\u7F6E\u6587\u4EF6 ${configFile} \u5931\u8D25:`, error);
685
+ console.log("\u63D0\u793A\uFF1A\u786E\u4FDD\u4F60\u7684\u9879\u76EE\u652F\u6301TypeScript\uFF0C\u6216\u8005\u4F7F\u7528 .js/.mjs \u914D\u7F6E\u6587\u4EF6");
686
+ } else {
687
+ console.error(`\u52A0\u8F7D\u914D\u7F6E\u6587\u4EF6 ${configFile} \u5931\u8D25:`, error);
688
+ }
689
+ }
690
+ }
469
691
  }
692
+ return null;
470
693
  }
471
- function createDevConfig(options, log) {
472
- const allFiles = import_glob2.glob.sync(options.entry, { cwd: process.cwd() });
473
- const entryFiles = filterEntryFiles(allFiles, options.entry, options.exclude, log);
474
- const input = {};
475
- entryFiles.forEach(({ name, file }) => {
476
- input[name] = path3.resolve(process.cwd(), file);
477
- });
478
- log("Dev input configuration:", input);
694
+
695
+ // src/types.ts
696
+ function defineConfig(config) {
697
+ return config;
698
+ }
699
+ function defineConfigTransform(transform) {
700
+ return transform;
479
701
  }
480
702
 
481
703
  // src/index.ts
482
- function viteMultiPage(options = {}) {
483
- const {
484
- entry = "src/**/*.{ts,js}",
485
- template = "index.html",
486
- exclude = ["src/main.ts", "src/vite-env.d.ts"],
487
- placeholder = "{{ENTRY_FILE}}",
488
- debug = false,
489
- buildStrategies,
490
- pageConfigs
491
- } = options;
492
- const log = createLogger(debug);
493
- let tempFiles = [];
494
- const pageMapping = /* @__PURE__ */ new Map();
704
+ function viteMultiPage(transform) {
705
+ let resolvedOptions;
706
+ const tempFiles = [];
707
+ let log = () => {
708
+ };
495
709
  return {
496
- name: "vite-plugin-multi-page",
497
- config(config, { command }) {
498
- if (command === "build") {
499
- createBuildConfig(
500
- config,
501
- { entry, exclude, template, placeholder, buildStrategies, pageConfigs },
502
- log,
503
- tempFiles,
504
- pageMapping
710
+ name: "vite-multi-page",
711
+ async configResolved(config) {
712
+ if (!hasCustomConfig()) {
713
+ throw new Error(
714
+ "\u672A\u627E\u5230\u591A\u9875\u9762\u914D\u7F6E\u6587\u4EF6\uFF01\u8BF7\u521B\u5EFA\u4EE5\u4E0B\u914D\u7F6E\u6587\u4EF6\u4E4B\u4E00\uFF1A\n - multipage.config.js\n - multipage.config.mjs\n - multipage.config.ts"
505
715
  );
506
- } else {
507
- createDevConfig({ entry, exclude }, log);
508
- if (buildStrategies || pageConfigs) {
509
- const allFiles = import_glob3.glob.sync(entry, { cwd: process.cwd() });
510
- const entryFiles = filterEntryFiles(allFiles, entry, exclude, log);
511
- const strategiesToApply = /* @__PURE__ */ new Set();
512
- entryFiles.forEach(({ name, file }) => {
513
- if (typeof pageConfigs === "function") {
514
- const pageConfig = pageConfigs({
515
- pageName: name,
516
- filePath: file,
517
- relativePath: path4.relative(process.cwd(), file),
518
- strategy: void 0,
519
- isMatched: false
520
- });
521
- if (pageConfig == null ? void 0 : pageConfig.strategy) {
522
- strategiesToApply.add(pageConfig.strategy);
523
- }
524
- } else if (pageConfigs) {
525
- const pageConfig = pageConfigs[name];
526
- if (pageConfig == null ? void 0 : pageConfig.strategy) {
527
- strategiesToApply.add(pageConfig.strategy);
528
- }
529
- }
716
+ }
717
+ const userConfig = await loadUserConfig({
718
+ mode: config.command === "serve" ? "development" : "production",
719
+ command: config.command,
720
+ isCLI: false
721
+ });
722
+ if (!userConfig) {
723
+ throw new Error("\u914D\u7F6E\u6587\u4EF6\u52A0\u8F7D\u5931\u8D25\uFF01");
724
+ }
725
+ resolvedOptions = transform ? transform(userConfig, {
726
+ mode: config.command === "serve" ? "development" : "production",
727
+ command: config.command,
728
+ isCLI: false
729
+ }) : userConfig;
730
+ const debug = resolvedOptions.debug ?? false;
731
+ log = debug ? console.log.bind(console, "[vite-multi-page]") : () => {
732
+ };
733
+ log("Vite\u914D\u7F6E\u5DF2\u89E3\u6790, \u4F7F\u7528\u914D\u7F6E:", {
734
+ strategies: Object.keys(resolvedOptions.strategies || {}),
735
+ entry: resolvedOptions.entry
736
+ });
737
+ },
738
+ async config(config, { command }) {
739
+ var _a;
740
+ if (command === "build") {
741
+ if (!resolvedOptions) {
742
+ if (!hasCustomConfig()) {
743
+ throw new Error(
744
+ "\u672A\u627E\u5230\u591A\u9875\u9762\u914D\u7F6E\u6587\u4EF6\uFF01\u8BF7\u521B\u5EFA\u4EE5\u4E0B\u914D\u7F6E\u6587\u4EF6\u4E4B\u4E00\uFF1A\n - multipage.config.js\n - multipage.config.mjs\n - multipage.config.ts"
745
+ );
746
+ }
747
+ const userConfig = await loadUserConfig({
748
+ mode: "production",
749
+ command: "build",
750
+ isCLI: false
530
751
  });
531
- strategiesToApply.forEach((strategyName) => {
532
- const strategy = buildStrategies == null ? void 0 : buildStrategies[strategyName];
533
- if (strategy) {
534
- log(`\u5F00\u53D1\u6A21\u5F0F\u5E94\u7528\u7B56\u7565 ${strategyName}:`, strategy);
535
- if (strategy.viteConfig) {
536
- const { build, ...otherViteConfig } = strategy.viteConfig;
537
- Object.keys(otherViteConfig).forEach((key) => {
538
- if (key !== "plugins") {
539
- const configKey = key;
540
- const viteConfigValue = otherViteConfig[key];
541
- if (viteConfigValue && typeof viteConfigValue === "object") {
542
- config[configKey] = {
543
- ...config[configKey] || {},
544
- ...viteConfigValue
545
- };
546
- } else {
547
- config[configKey] = viteConfigValue;
548
- }
549
- }
550
- });
551
- }
552
- if (strategy.define) {
553
- config.define = { ...config.define, ...strategy.define };
554
- }
555
- if (strategy.alias) {
556
- config.resolve = config.resolve || {};
557
- config.resolve.alias = { ...config.resolve.alias, ...strategy.alias };
558
- }
559
- if (strategy.server) {
560
- config.server = { ...config.server, ...strategy.server };
561
- }
562
- if (strategy.css) {
563
- config.css = { ...config.css, ...strategy.css };
564
- }
565
- if (strategy.optimizeDeps) {
566
- config.optimizeDeps = { ...config.optimizeDeps, ...strategy.optimizeDeps };
567
- }
568
- }
752
+ if (!userConfig) {
753
+ throw new Error("\u914D\u7F6E\u6587\u4EF6\u52A0\u8F7D\u5931\u8D25\uFF01");
754
+ }
755
+ resolvedOptions = transform ? transform(userConfig, {
756
+ mode: "production",
757
+ command: "build",
758
+ isCLI: false
759
+ }) : userConfig;
760
+ const debug = resolvedOptions.debug ?? false;
761
+ log = debug ? console.log.bind(console, "[vite-multi-page]") : () => {
762
+ };
763
+ }
764
+ log("\u914D\u7F6E\u6784\u5EFA\u6A21\u5F0F");
765
+ const forceBuildStrategy = process.env.VITE_BUILD_STRATEGY;
766
+ const buildConfigs = generateBuildConfig({
767
+ entry: resolvedOptions.entry || "src/pages/**/*.{ts,js}",
768
+ exclude: resolvedOptions.exclude || [],
769
+ template: resolvedOptions.template || "index.html",
770
+ placeholder: resolvedOptions.placeholder || "{{ENTRY_FILE}}",
771
+ strategies: resolvedOptions.strategies || {},
772
+ pageConfigs: resolvedOptions.pageConfigs || {},
773
+ forceBuildStrategy
774
+ });
775
+ const targetStrategy = Object.keys(buildConfigs)[0];
776
+ if (targetStrategy && buildConfigs[targetStrategy]) {
777
+ log(`\u5E94\u7528\u6784\u5EFA\u7B56\u7565: ${targetStrategy}`);
778
+ const strategyConfig = buildConfigs[targetStrategy];
779
+ const mergedConfig = (0, import_vite2.mergeConfig)(config, strategyConfig);
780
+ Object.assign(config, mergedConfig);
781
+ log(`\u5DF2\u5E94\u7528\u7B56\u7565 "${targetStrategy}" \u7684\u914D\u7F6E:`, {
782
+ build: !!strategyConfig.build,
783
+ define: !!strategyConfig.define,
784
+ plugins: ((_a = strategyConfig.plugins) == null ? void 0 : _a.length) || 0
569
785
  });
786
+ } else {
787
+ log("\u672A\u627E\u5230\u53EF\u7528\u7684\u6784\u5EFA\u7B56\u7565\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u914D\u7F6E");
570
788
  }
571
789
  }
572
790
  },
573
791
  configureServer(server) {
574
- configureDevServer(
575
- server,
576
- { entry, exclude, template, placeholder, buildStrategies, pageConfigs },
577
- log
578
- );
579
- },
580
- generateBundle() {
581
- },
582
- writeBundle(options2) {
583
- Array.from(pageMapping.entries()).forEach(([tempName, targetName]) => {
584
- const tempPath = path4.resolve(options2.dir || "dist", tempName);
585
- const targetPath = path4.resolve(options2.dir || "dist", targetName);
586
- if (fs3.existsSync(tempPath)) {
587
- fs3.renameSync(tempPath, targetPath);
588
- log(`\u91CD\u547D\u540DHTML\u6587\u4EF6: ${tempName} -> ${targetName}`);
589
- }
590
- });
792
+ if (server.config.command === "serve") {
793
+ log("\u914D\u7F6E\u5F00\u53D1\u670D\u52A1\u5668");
794
+ setupDevMiddleware(
795
+ server,
796
+ {
797
+ entry: resolvedOptions.entry || "src/pages/**/*.{ts,js}",
798
+ exclude: resolvedOptions.exclude || [],
799
+ template: resolvedOptions.template || "index.html",
800
+ placeholder: resolvedOptions.placeholder || "{{ENTRY_FILE}}",
801
+ strategies: resolvedOptions.strategies || {},
802
+ pageConfigs: resolvedOptions.pageConfigs || {}
803
+ },
804
+ log
805
+ );
806
+ }
591
807
  },
592
- closeBundle() {
593
- tempFiles.forEach((filePath) => {
594
- if (fs3.existsSync(filePath)) {
595
- fs3.unlinkSync(filePath);
596
- const fileName = path4.basename(filePath);
597
- log(`\u6E05\u7406\u4E34\u65F6\u6587\u4EF6: ${fileName}`);
598
- }
599
- });
600
- tempFiles = [];
601
- pageMapping.clear();
808
+ buildEnd() {
809
+ if (tempFiles.length > 0) {
810
+ log(`\u6E05\u7406 ${tempFiles.length} \u4E2A\u4E34\u65F6\u6587\u4EF6`);
811
+ tempFiles.forEach((file) => {
812
+ try {
813
+ if (fs4.existsSync(file)) {
814
+ fs4.unlinkSync(file);
815
+ log(`\u5220\u9664\u4E34\u65F6\u6587\u4EF6: ${file}`);
816
+ }
817
+ } catch (error) {
818
+ log(`\u5220\u9664\u4E34\u65F6\u6587\u4EF6\u5931\u8D25: ${file}`, error);
819
+ }
820
+ });
821
+ tempFiles.length = 0;
822
+ }
602
823
  }
603
824
  };
604
825
  }
605
826
  var src_default = viteMultiPage;
606
827
  // Annotate the CommonJS export names for ESM import in node:
607
828
  0 && (module.exports = {
829
+ defineConfig,
830
+ defineConfigTransform,
831
+ generateBuildConfig,
832
+ getAvailableStrategies,
608
833
  viteMultiPage
609
834
  });
610
835
  //# sourceMappingURL=index.js.map