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