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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,908 +1,24 @@
1
1
  #!/usr/bin/env node
2
- "use strict";
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __esm = (fn, res) => function __init() {
10
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
- };
12
- var __export = (target, all) => {
13
- for (var name in all)
14
- __defProp(target, name, { get: all[name], enumerable: true });
15
- };
16
- var __copyProps = (to, from, except, desc) => {
17
- if (from && typeof from === "object" || typeof from === "function") {
18
- for (let key of __getOwnPropNames(from))
19
- if (!__hasOwnProp.call(to, key) && key !== except)
20
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
- }
22
- return to;
23
- };
24
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
- // If the importer is in node compatibility mode or this is not an ESM
26
- // file that has been converted to a CommonJS file using a Babel-
27
- // compatible transform (i.e. "__esModule" has not been set), then set
28
- // "default" to the CommonJS "module.exports" for node compatibility.
29
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
- mod
31
- ));
32
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
33
-
34
- // node_modules/.pnpm/tsup@8.0.0_typescript@5.0.2/node_modules/tsup/assets/cjs_shims.js
35
- var init_cjs_shims = __esm({
36
- "node_modules/.pnpm/tsup@8.0.0_typescript@5.0.2/node_modules/tsup/assets/cjs_shims.js"() {
37
- "use strict";
38
- }
39
- });
40
-
41
- // src/file-filter.ts
42
- function filterEntryFiles(files, entry, exclude, _log) {
43
- const result = [];
44
- const nameToFile = /* @__PURE__ */ new Map();
45
- let basePattern = entry.replace(/\/\*.*$/, "");
46
- if (!basePattern || basePattern === entry) {
47
- basePattern = path.dirname(entry.split("*")[0]);
48
- }
49
- const candidateFiles = [];
50
- for (const file of files) {
51
- if (exclude.includes(file)) {
52
- continue;
53
- }
54
- const relativePath = path.relative(basePattern, file);
55
- const pathParts = relativePath.split(path.sep);
56
- if (pathParts.length === 1) {
57
- const fileName = pathParts[0];
58
- const name = path.basename(fileName, path.extname(fileName));
59
- candidateFiles.push({ name, file, priority: 1 });
60
- } else if (pathParts.length >= 2) {
61
- const fileName = path.basename(file, path.extname(file));
62
- const dirName = pathParts[0];
63
- if (fileName === "main") {
64
- candidateFiles.push({ name: dirName, file, priority: 2 });
65
- }
66
- }
67
- }
68
- for (const candidate of candidateFiles) {
69
- const existing = nameToFile.get(candidate.name);
70
- if (!existing) {
71
- nameToFile.set(candidate.name, { file: candidate.file, priority: candidate.priority });
72
- } else {
73
- if (candidate.priority > existing.priority) {
74
- nameToFile.set(candidate.name, { file: candidate.file, priority: candidate.priority });
75
- }
76
- }
77
- }
78
- for (const [name, { file }] of nameToFile.entries()) {
79
- result.push({ name, file });
80
- }
81
- return result;
82
- }
83
- var path;
84
- var init_file_filter = __esm({
85
- "src/file-filter.ts"() {
86
- "use strict";
87
- init_cjs_shims();
88
- path = __toESM(require("path"));
89
- }
90
- });
91
-
92
- // src/page-config.ts
93
- function getPageConfig(pageConfigs, context, log) {
94
- if (!pageConfigs)
95
- return null;
96
- if (typeof pageConfigs === "function") {
97
- const result = pageConfigs(context);
98
- if (result) {
99
- }
100
- return result;
101
- }
102
- for (const [key, config] of Object.entries(pageConfigs)) {
103
- if (key === context.pageName) {
104
- log(`\u7CBE\u786E\u5339\u914D\u9875\u9762 ${context.pageName}:`, config);
105
- return config;
106
- }
107
- if (config.match) {
108
- const patterns = Array.isArray(config.match) ? config.match : [config.match];
109
- const isMatched = patterns.some(
110
- (pattern) => simpleMatch(pattern, context.pageName) || simpleMatch(pattern, context.relativePath) || simpleMatch(pattern, context.filePath)
111
- );
112
- if (isMatched) {
113
- log(`\u6A21\u5F0F\u5339\u914D\u9875\u9762 ${context.pageName} (\u6A21\u5F0F: ${config.match}):`, config);
114
- return { ...config, match: void 0 };
115
- }
116
- }
117
- if (simpleMatch(key, context.pageName)) {
118
- log(`Glob\u5339\u914D\u9875\u9762 ${context.pageName} (\u6A21\u5F0F: ${key}):`, config);
119
- return config;
120
- }
121
- }
122
- return null;
123
- }
124
- function simpleMatch(pattern, text) {
125
- const regexPattern = pattern.replace(/\*\*/g, "__DOUBLE_STAR__").replace(/\*/g, "[^/]*").replace(/__DOUBLE_STAR__/g, ".*");
126
- const regex = new RegExp(`^${regexPattern}$`);
127
- return regex.test(text);
128
- }
129
- var init_page_config = __esm({
130
- "src/page-config.ts"() {
131
- "use strict";
132
- init_cjs_shims();
133
- }
134
- });
135
-
136
- // src/utils.ts
137
- function createLogger(debug) {
138
- return (...args) => {
139
- if (debug) {
140
- console.log("[vite-plugin-multi-page]", ...args);
141
- }
142
- };
143
- }
144
- var init_utils = __esm({
145
- "src/utils.ts"() {
146
- "use strict";
147
- init_cjs_shims();
148
- }
149
- });
150
-
151
- // src/build-config.ts
152
- var build_config_exports = {};
153
- __export(build_config_exports, {
154
- cleanViteOutputDirectory: () => cleanViteOutputDirectory,
155
- generateBuildConfig: () => generateBuildConfig,
156
- getAvailableStrategies: () => getAvailableStrategies,
157
- getViteOutputDirectory: () => getViteOutputDirectory
158
- });
159
- function generateBuildConfig(options) {
160
- var _a;
161
- const {
162
- entry = "src/pages/*/main.{ts,js}",
163
- exclude = [],
164
- template = "index.html",
165
- placeholder = "<!--VITE_MULTI_PAGE_ENTRY-->",
166
- strategies = {},
167
- pageConfigs = {},
168
- forceBuildStrategy
169
- } = options;
170
- const log = createLogger(true);
171
- const buildConfigs = {};
172
- try {
173
- const allFiles = import_glob.glob.sync(entry, { cwd: process.cwd() });
174
- const entryFiles = filterEntryFiles(allFiles, entry, exclude, log);
175
- if (entryFiles.length === 0) {
176
- log("\u8B66\u544A: \u672A\u627E\u5230\u5339\u914D\u7684\u5165\u53E3\u6587\u4EF6");
177
- return {};
178
- }
179
- const pageStrategies = /* @__PURE__ */ new Map();
180
- const strategyPages = /* @__PURE__ */ new Map();
181
- for (const entryFile of entryFiles) {
182
- const pageContext = {
183
- pageName: entryFile.name,
184
- filePath: entryFile.file,
185
- relativePath: path2.relative(process.cwd(), entryFile.file)
186
- };
187
- const pageConfig = getPageConfig(pageConfigs, pageContext, log);
188
- const strategyName = (pageConfig == null ? void 0 : pageConfig.strategy) || "default";
189
- pageStrategies.set(entryFile.name, strategyName);
190
- if (!strategyPages.has(strategyName)) {
191
- strategyPages.set(strategyName, []);
192
- }
193
- (_a = strategyPages.get(strategyName)) == null ? void 0 : _a.push(entryFile.name);
194
- }
195
- log(`\u{1F4C4} \u53D1\u73B0 ${entryFiles.length} \u4E2A\u9875\u9762: ${entryFiles.map((f) => f.name).join(", ")}`);
196
- if (forceBuildStrategy) {
197
- const targetPages = strategyPages.get(forceBuildStrategy) || [];
198
- if (targetPages.length === 0) {
199
- log(`\u8B66\u544A: \u7B56\u7565 "${forceBuildStrategy}" \u4E0B\u6CA1\u6709\u9875\u9762`);
200
- return {};
201
- }
202
- log(`\u5F3A\u5236\u6784\u5EFA\u7B56\u7565: ${forceBuildStrategy}, \u9875\u9762: ${targetPages.join(", ")}`);
203
- const config = generateStrategyConfig(
204
- forceBuildStrategy,
205
- targetPages,
206
- entryFiles,
207
- strategies[forceBuildStrategy],
208
- pageConfigs,
209
- template,
210
- placeholder,
211
- log
212
- );
213
- buildConfigs[forceBuildStrategy] = config;
214
- return buildConfigs;
215
- }
216
- for (const [strategyName, pages] of strategyPages) {
217
- if (pages.length === 0)
218
- continue;
219
- const strategyConfig = strategies[strategyName] || {};
220
- const config = generateStrategyConfig(
221
- strategyName,
222
- pages,
223
- entryFiles,
224
- strategyConfig,
225
- pageConfigs,
226
- template,
227
- placeholder,
228
- log
229
- );
230
- buildConfigs[strategyName] = config;
231
- }
232
- if (Object.keys(buildConfigs).length === 0) {
233
- log("\u8B66\u544A: \u672A\u751F\u6210\u4EFB\u4F55\u6784\u5EFA\u914D\u7F6E\uFF0C\u521B\u5EFA\u9ED8\u8BA4\u914D\u7F6E");
234
- const allPageNames = entryFiles.map((f) => f.name);
235
- const defaultConfig = generateStrategyConfig(
236
- "default",
237
- allPageNames,
238
- entryFiles,
239
- {},
240
- pageConfigs,
241
- template,
242
- placeholder,
243
- log
244
- );
245
- buildConfigs["default"] = defaultConfig;
246
- }
247
- const strategyNames = Object.keys(buildConfigs);
248
- log(`\u{1F4E6} \u6784\u5EFA\u7B56\u7565: ${strategyNames.join(", ")}`);
249
- return buildConfigs;
250
- } catch (error) {
251
- log("\u751F\u6210\u6784\u5EFA\u914D\u7F6E\u5931\u8D25:", error);
252
- throw error;
253
- }
254
- }
255
- function generateStrategyConfig(strategyName, pages, entryFiles, strategyConfig, pageConfigs, defaultTemplate, placeholder, log) {
256
- const htmlInputs = {};
257
- const tempFiles = [];
258
- const allPageDefines = {};
259
- for (const pageName of pages) {
260
- const entryFile = entryFiles.find((f) => f.name === pageName);
261
- if (!entryFile)
262
- continue;
263
- const pageContext = {
264
- pageName,
265
- filePath: entryFile.file,
266
- relativePath: path2.relative(process.cwd(), entryFile.file),
267
- strategy: strategyName
268
- };
269
- const pageConfig = getPageConfig(pageConfigs, pageContext, log);
270
- if (pageConfig == null ? void 0 : pageConfig.define) {
271
- Object.assign(allPageDefines, pageConfig.define);
272
- }
273
- let templatePath = defaultTemplate;
274
- const pageSpecificTemplate = `${pageName}.html`;
275
- if (fs.existsSync(path2.resolve(process.cwd(), pageSpecificTemplate))) {
276
- templatePath = pageSpecificTemplate;
277
- } else if (pageConfig == null ? void 0 : pageConfig.template) {
278
- templatePath = pageConfig.template;
279
- }
280
- const templateFullPath = path2.resolve(process.cwd(), templatePath);
281
- if (!fs.existsSync(templateFullPath)) {
282
- log(`\u8B66\u544A: \u6A21\u677F\u6587\u4EF6\u4E0D\u5B58\u5728: ${templatePath}`);
283
- continue;
284
- }
285
- let templateContent = fs.readFileSync(templateFullPath, "utf-8");
286
- if (templateContent.includes(placeholder)) {
287
- const entryPath = `./${entryFile.file}`;
288
- templateContent = templateContent.replace(
289
- new RegExp(placeholder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"),
290
- entryPath
291
- );
292
- }
293
- const tempHtmlPath = path2.resolve(process.cwd(), `.temp.mp.${pageName}.html`);
294
- fs.writeFileSync(tempHtmlPath, templateContent);
295
- tempFiles.push(tempHtmlPath);
296
- htmlInputs[pageName] = tempHtmlPath;
297
- }
298
- const baseConfig = {
299
- build: {
300
- rollupOptions: {
301
- input: htmlInputs,
302
- // 使用临时HTML文件作为输入
303
- output: {
304
- entryFileNames: "assets/[name]-[hash].js",
305
- chunkFileNames: "assets/[name]-[hash].js",
306
- assetFileNames: "assets/[name]-[hash][extname]"
307
- }
308
- },
309
- emptyOutDir: false
310
- // 不清空输出目录,避免删除临时HTML文件
311
- },
312
- define: {}
313
- };
314
- let config = baseConfig;
315
- if (strategyConfig) {
316
- config = (0, import_vite.mergeConfig)(baseConfig, strategyConfig);
317
- }
318
- if (Object.keys(allPageDefines).length > 0) {
319
- config.define = {
320
- ...config.define,
321
- ...allPageDefines
322
- };
323
- }
324
- if (!config.build)
325
- config.build = {};
326
- if (!config.build.rollupOptions)
327
- config.build.rollupOptions = {};
328
- config.build.rollupOptions.input = htmlInputs;
329
- config.build.emptyOutDir = false;
330
- log(`\u7B56\u7565 "${strategyName}" - ${pages.length} \u4E2A\u9875\u9762`);
331
- return config;
332
- }
333
- function getViteOutputDirectory(viteBuildArgs = []) {
334
- const outDirIndex = viteBuildArgs.findIndex((arg) => arg === "--outDir");
335
- if (outDirIndex !== -1 && outDirIndex + 1 < viteBuildArgs.length) {
336
- const outDir = viteBuildArgs[outDirIndex + 1];
337
- return path2.resolve(process.cwd(), outDir);
338
- }
339
- const outDirArg = viteBuildArgs.find((arg) => arg.startsWith("--outDir="));
340
- if (outDirArg) {
341
- const outDir = outDirArg.split("=")[1];
342
- return path2.resolve(process.cwd(), outDir);
343
- }
344
- return path2.resolve(process.cwd(), "dist");
345
- }
346
- function cleanViteOutputDirectory(viteBuildArgs = []) {
347
- const outputDir = getViteOutputDirectory(viteBuildArgs);
348
- const log = createLogger(true);
349
- try {
350
- if (fs.existsSync(outputDir)) {
351
- fs.rmSync(outputDir, { recursive: true, force: true });
352
- log(`\u{1F9F9} \u6E05\u7406\u8F93\u51FA\u76EE\u5F55: ${path2.relative(process.cwd(), outputDir)}`);
353
- }
354
- } catch (error) {
355
- log(`\u26A0\uFE0F \u6E05\u7406\u8F93\u51FA\u76EE\u5F55\u5931\u8D25: ${outputDir}`, error);
356
- }
357
- }
358
- function getAvailableStrategies(options) {
359
- const { entry = "src/pages/*/main.{ts,js}", exclude = [], pageConfigs = {} } = options;
360
- const log = createLogger(false);
361
- const strategySet = /* @__PURE__ */ new Set();
362
- const allFiles = import_glob.glob.sync(entry, { cwd: process.cwd() });
363
- const entryFiles = filterEntryFiles(allFiles, entry, exclude, log);
364
- if (entryFiles.length === 0) {
365
- throw new Error(`\u672A\u627E\u5230\u5339\u914D\u7684\u5165\u53E3\u6587\u4EF6: ${entry}`);
366
- }
367
- try {
368
- for (const entryFile of entryFiles) {
369
- const pageContext = {
370
- pageName: entryFile.name,
371
- filePath: entryFile.file,
372
- relativePath: path2.relative(process.cwd(), entryFile.file)
373
- };
374
- const pageConfig = getPageConfig(pageConfigs, pageContext, log);
375
- const strategyName = (pageConfig == null ? void 0 : pageConfig.strategy) || "default";
376
- strategySet.add(strategyName);
377
- }
378
- return Array.from(strategySet).sort();
379
- } catch (error) {
380
- log("\u83B7\u53D6\u53EF\u7528\u7B56\u7565\u5931\u8D25:", error);
381
- return ["default"];
382
- }
383
- }
384
- var import_vite, import_glob, path2, fs;
385
- var init_build_config = __esm({
386
- "src/build-config.ts"() {
387
- "use strict";
388
- init_cjs_shims();
389
- import_vite = require("vite");
390
- import_glob = require("glob");
391
- path2 = __toESM(require("path"));
392
- fs = __toESM(require("fs"));
393
- init_file_filter();
394
- init_page_config();
395
- init_utils();
396
- }
397
- });
398
-
399
- // src/config-loader.ts
400
- var config_loader_exports = {};
401
- __export(config_loader_exports, {
402
- hasCustomConfig: () => hasCustomConfig,
403
- loadUserConfig: () => loadUserConfig
404
- });
405
- function hasCustomConfig() {
406
- for (const filename of CONFIG_FILES) {
407
- const configPath = path3.resolve(process.cwd(), filename);
408
- if (fs2.existsSync(configPath)) {
409
- return true;
410
- }
411
- }
412
- return false;
413
- }
414
- async function loadUserConfig(context) {
415
- const customConfig = await loadCustomConfig();
416
- if (customConfig) {
417
- const result = customConfig(context);
418
- if (!result) {
419
- return {};
420
- }
421
- return result;
422
- }
423
- return null;
424
- }
425
- async function loadConfigFile(filePath) {
426
- if (filePath.endsWith(".ts")) {
427
- try {
428
- const code = await fs2.promises.readFile(filePath, "utf-8");
429
- const esbuild = await import("esbuild");
430
- const result = await esbuild.transform(code, {
431
- loader: "ts",
432
- format: "cjs",
433
- // 使用 CommonJS 格式便于使用 Module._compile
434
- target: "node16",
435
- sourcemap: false
436
- });
437
- const tempModule = new import_node_module.Module(filePath);
438
- tempModule.filename = filePath;
439
- tempModule.paths = import_node_module.Module._nodeModulePaths(path3.dirname(filePath));
440
- tempModule._compile(result.code, filePath);
441
- return tempModule.exports;
442
- } catch (esbuildError) {
443
- console.warn("esbuild \u8F6C\u8BD1\u5931\u8D25\uFF0C\u5C1D\u8BD5\u7B80\u5355\u8F6C\u6362:", esbuildError);
444
- const code = await fs2.promises.readFile(filePath, "utf-8");
445
- const jsCode = code.replace(/export\s+default\s+/, "module.exports = ").replace(/import\s+.*?from\s+['"][^'"]*['"];?\s*/g, "").replace(/:\s*[^=,})\]]+/g, "");
446
- const tempModule = new import_node_module.Module(filePath);
447
- tempModule.filename = filePath;
448
- tempModule.paths = import_node_module.Module._nodeModulePaths(path3.dirname(filePath));
449
- tempModule._compile(jsCode, filePath);
450
- return tempModule.exports;
451
- }
452
- }
453
- if (filePath.endsWith(".js") || filePath.endsWith(".mjs")) {
454
- const fileUrl = (0, import_node_url.pathToFileURL)(filePath).href;
455
- return import(`${fileUrl}?t=${Date.now()}`);
456
- }
457
- throw new Error(`\u4E0D\u652F\u6301\u7684\u914D\u7F6E\u6587\u4EF6\u7C7B\u578B: ${filePath}`);
458
- }
459
- async function loadCustomConfig() {
460
- const cwd = process.cwd();
461
- for (const configFile of CONFIG_FILES) {
462
- const configPath = path3.resolve(cwd, configFile);
463
- if (fs2.existsSync(configPath)) {
464
- try {
465
- const configModule = await loadConfigFile(configPath);
466
- const configFunction = configModule.default || configModule;
467
- if (typeof configFunction === "function") {
468
- return configFunction;
469
- } else {
470
- console.warn(`\u914D\u7F6E\u6587\u4EF6 ${configFile} \u5FC5\u987B\u9ED8\u8BA4\u5BFC\u51FA\u4E00\u4E2A\u51FD\u6570`);
471
- }
472
- } catch (error) {
473
- if (configFile.endsWith(".ts")) {
474
- console.error(`\u52A0\u8F7DTypeScript\u914D\u7F6E\u6587\u4EF6 ${configFile} \u5931\u8D25:`, error);
475
- console.log("\u63D0\u793A\uFF1A\u786E\u4FDD\u4F60\u7684\u9879\u76EE\u652F\u6301TypeScript\uFF0C\u6216\u8005\u4F7F\u7528 .js/.mjs \u914D\u7F6E\u6587\u4EF6");
476
- } else {
477
- console.error(`\u52A0\u8F7D\u914D\u7F6E\u6587\u4EF6 ${configFile} \u5931\u8D25:`, error);
478
- }
479
- }
480
- }
481
- }
482
- return null;
483
- }
484
- var fs2, path3, import_node_url, import_node_module, CONFIG_FILES;
485
- var init_config_loader = __esm({
486
- "src/config-loader.ts"() {
487
- "use strict";
488
- init_cjs_shims();
489
- fs2 = __toESM(require("fs"));
490
- path3 = __toESM(require("path"));
491
- import_node_url = require("url");
492
- import_node_module = require("module");
493
- CONFIG_FILES = [
494
- "multipage.config.js",
495
- "multipage.config.mjs",
496
- "multipage.config.ts"
497
- ];
498
- }
499
- });
500
-
501
- // src/defaults.ts
502
- var defaults_exports = {};
503
- __export(defaults_exports, {
504
- DEFAULT_CONFIG: () => DEFAULT_CONFIG,
505
- isEmptyConfig: () => isEmptyConfig,
506
- mergeWithDefaults: () => mergeWithDefaults
507
- });
508
- function mergeWithDefaults(userConfig) {
509
- if (!userConfig) {
510
- return { ...DEFAULT_CONFIG };
511
- }
512
- return {
513
- entry: userConfig.entry ?? DEFAULT_CONFIG.entry,
514
- exclude: userConfig.exclude ?? DEFAULT_CONFIG.exclude,
515
- template: userConfig.template ?? DEFAULT_CONFIG.template,
516
- placeholder: userConfig.placeholder ?? DEFAULT_CONFIG.placeholder,
517
- debug: userConfig.debug ?? DEFAULT_CONFIG.debug,
518
- strategies: userConfig.strategies ?? DEFAULT_CONFIG.strategies,
519
- pageConfigs: userConfig.pageConfigs ?? DEFAULT_CONFIG.pageConfigs,
520
- __forceBuildStrategy: userConfig.__forceBuildStrategy
521
- };
522
- }
523
- function isEmptyConfig(config) {
524
- if (Object.keys(config).length === 0) {
525
- return true;
526
- }
527
- const hasValidEntry = config.entry && config.entry !== DEFAULT_CONFIG.entry;
528
- const hasValidStrategies = config.strategies && Object.keys(config.strategies).length > 0;
529
- const hasValidPageConfigs = config.pageConfigs && (typeof config.pageConfigs === "function" || Object.keys(config.pageConfigs).length > 0);
530
- return !hasValidEntry && !hasValidStrategies && !hasValidPageConfigs;
531
- }
532
- var DEFAULT_CONFIG;
533
- var init_defaults = __esm({
534
- "src/defaults.ts"() {
535
- "use strict";
536
- init_cjs_shims();
537
- DEFAULT_CONFIG = {
538
- entry: "src/pages/**/*.{ts,js}",
539
- exclude: [],
540
- template: "index.html",
541
- placeholder: "{{ENTRY_FILE}}",
542
- debug: false,
543
- strategies: {
544
- default: {}
545
- },
546
- pageConfigs: {}
547
- };
548
- }
549
- });
550
-
551
- // src/cli.ts
552
- var cli_exports = {};
553
- __export(cli_exports, {
554
- buildAll: () => main
555
- });
556
- module.exports = __toCommonJS(cli_exports);
557
- init_cjs_shims();
558
- var import_node_child_process = require("child_process");
559
- var fs3 = __toESM(require("fs"));
560
- var path4 = __toESM(require("path"));
561
- var glob2 = __toESM(require("glob"));
562
- init_build_config();
563
- function parseArgs() {
564
- const args = process.argv.slice(2);
565
- const viteBuildArgs = [];
566
- let debug = false;
567
- let cwd;
568
- for (let i = 0; i < args.length; i++) {
569
- const arg = args[i];
570
- if (arg === "--debug") {
571
- debug = true;
572
- } else if (arg === "--cwd") {
573
- cwd = args[++i];
574
- } else if (arg === "--help" || arg === "-h") {
575
- console.log(`
576
- \u4F7F\u7528\u65B9\u6CD5: vite-multi-page-build [\u9009\u9879]
2
+ "use strict";var ae=Object.create;var L=Object.defineProperty;var ce=Object.getOwnPropertyDescriptor;var le=Object.getOwnPropertyNames;var pe=Object.getPrototypeOf,fe=Object.prototype.hasOwnProperty;var D=(e,t)=>()=>(e&&(t=e(e=0)),t);var A=(e,t)=>{for(var s in t)L(e,s,{get:t[s],enumerable:!0})},z=(e,t,s,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of le(t))!fe.call(e,n)&&n!==s&&L(e,n,{get:()=>t[n],enumerable:!(o=ce(t,n))||o.enumerable});return e};var P=(e,t,s)=>(s=e!=null?ae(pe(e)):{},z(t||!e||!e.__esModule?L(s,"default",{value:e,enumerable:!0}):s,e)),ge=e=>z(L({},"__esModule",{value:!0}),e);var w=D(()=>{"use strict"});function G(e,t,s,o){let n=[],i=new Map,f=t.replace(/\/\*.*$/,"");(!f||f===t)&&(f=O.dirname(t.split("*")[0]));let a=[];for(let r of e){if(s.includes(r))continue;let u=r.replace(/\\/g,"/"),l=f.replace(/\\/g,"/"),p=O.posix.relative(l,u).split("/");if(p.length===1){let $=p[0],g=O.posix.basename($,O.posix.extname($));a.push({name:g,file:r,priority:1})}else if(p.length>=2){let $=O.posix.basename(u,O.posix.extname(u)),g=p[0];$==="main"&&a.push({name:g,file:r,priority:2})}}for(let r of a){let u=i.get(r.name);u?r.priority>u.priority&&i.set(r.name,{file:r.file,priority:r.priority}):i.set(r.name,{file:r.file,priority:r.priority})}for(let[r,{file:u}]of i.entries())n.push({name:r,file:u});return n}var O,J=D(()=>{"use strict";w();O=P(require("path"))});function k(e,t,s){if(!e)return null;if(typeof e=="function"){let o=e(t);return o}for(let[o,n]of Object.entries(e)){if(o===t.pageName)return s(`\u7CBE\u786E\u5339\u914D\u9875\u9762 ${t.pageName}:`,n),n;if(n.match&&(Array.isArray(n.match)?n.match:[n.match]).some(a=>I(a,t.pageName)||I(a,t.relativePath)||I(a,t.filePath)))return s(`\u6A21\u5F0F\u5339\u914D\u9875\u9762 ${t.pageName} (\u6A21\u5F0F: ${n.match}):`,n),{...n,match:void 0};if(I(o,t.pageName))return s(`Glob\u5339\u914D\u9875\u9762 ${t.pageName} (\u6A21\u5F0F: ${o}):`,n),n}return null}function I(e,t){let s=e.replace(/\*\*/g,"__DOUBLE_STAR__").replace(/\*/g,"[^/]*").replace(/__DOUBLE_STAR__/g,".*");return new RegExp(`^${s}$`).test(t)}var K=D(()=>{"use strict";w()});function B(e){return(...t)=>{e&&console.log("[vite-plugin-multi-page]",...t)}}var Q=D(()=>{"use strict";w()});var q={};A(q,{cleanViteOutputDirectory:()=>ue,generateBuildConfig:()=>me,getAvailableStrategies:()=>de,getViteOutputDirectory:()=>R});function me(e){var l;let{entry:t="src/pages/*/main.{ts,js}",exclude:s=[],template:o="index.html",placeholder:n="<!--VITE_MULTI_PAGE_ENTRY-->",strategies:i={},pageConfigs:f={},forceBuildStrategy:a}=e,r=B(!0),u={};try{let d=Y.glob.sync(t,{cwd:process.cwd()}),p=G(d,t,s,r);if(p.length===0)return r("\u8B66\u544A: \u672A\u627E\u5230\u5339\u914D\u7684\u5165\u53E3\u6587\u4EF6"),{};let $=new Map,g=new Map;for(let c of p){let h={pageName:c.name,filePath:c.file,relativePath:C.relative(process.cwd(),c.file)},b=k(f,h,r),v=(b==null?void 0:b.strategy)||"default";$.set(c.name,v),g.has(v)||g.set(v,[]),(l=g.get(v))==null||l.push(c.name)}if(r(`\u{1F4C4} \u53D1\u73B0 ${p.length} \u4E2A\u9875\u9762: ${p.map(c=>c.name).join(", ")}`),a){let c=g.get(a)||[];if(c.length===0)return r(`\u8B66\u544A: \u7B56\u7565 "${a}" \u4E0B\u6CA1\u6709\u9875\u9762`),{};r(`\u5F3A\u5236\u6784\u5EFA\u7B56\u7565: ${a}, \u9875\u9762: ${c.join(", ")}`);let h=H(a,c,p,i[a],f,o,n,r);return u[a]=h,u}for(let[c,h]of g){if(h.length===0)continue;let b=i[c]||{},v=H(c,h,p,b,f,o,n,r);u[c]=v}if(Object.keys(u).length===0){r("\u8B66\u544A: \u672A\u751F\u6210\u4EFB\u4F55\u6784\u5EFA\u914D\u7F6E\uFF0C\u521B\u5EFA\u9ED8\u8BA4\u914D\u7F6E");let c=p.map(b=>b.name),h=H("default",c,p,{},f,o,n,r);u.default=h}let x=Object.keys(u);return r(`\u{1F4E6} \u6784\u5EFA\u7B56\u7565: ${x.join(", ")}`),u}catch(d){throw r("\u751F\u6210\u6784\u5EFA\u914D\u7F6E\u5931\u8D25:",d),d}}function H(e,t,s,o,n,i,f,a){let r={},u=[],l={};for(let $ of t){let g=s.find(M=>M.name===$);if(!g)continue;let x={pageName:$,filePath:g.file,relativePath:C.relative(process.cwd(),g.file),strategy:e},c=k(n,x,a);c!=null&&c.define&&Object.assign(l,c.define);let h=i,b=`${$}.html`;S.existsSync(C.resolve(process.cwd(),b))?h=b:c!=null&&c.template&&(h=c.template);let v=C.resolve(process.cwd(),h);if(!S.existsSync(v)){a(`\u8B66\u544A: \u6A21\u677F\u6587\u4EF6\u4E0D\u5B58\u5728: ${h}`);continue}let N=S.readFileSync(v,"utf-8");if(N.includes(f)){let M=`./${g.file}`;N=N.replace(new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),M)}let j=C.resolve(process.cwd(),`.temp.mp.${$}.html`);S.writeFileSync(j,N),u.push(j),r[$]=j}let d={build:{rollupOptions:{input:r,output:{entryFileNames:"assets/[name]-[hash].js",chunkFileNames:"assets/[name]-[hash].js",assetFileNames:"assets/[name]-[hash][extname]"}},emptyOutDir:!1},define:{}},p=d;return o&&(p=(0,X.mergeConfig)(d,o)),Object.keys(l).length>0&&(p.define={...p.define,...l}),p.build||(p.build={}),p.build.rollupOptions||(p.build.rollupOptions={}),p.build.rollupOptions.input=r,p.build.emptyOutDir=!1,a(`\u7B56\u7565 "${e}" - ${t.length} \u4E2A\u9875\u9762`),p}function R(e=[]){let t=e.findIndex(o=>o==="--outDir");if(t!==-1&&t+1<e.length){let o=e[t+1];return C.resolve(process.cwd(),o)}let s=e.find(o=>o.startsWith("--outDir="));if(s){let o=s.split("=")[1];return C.resolve(process.cwd(),o)}return C.resolve(process.cwd(),"dist")}function ue(e=[]){let t=R(e),s=B(!0);try{S.existsSync(t)&&(S.rmSync(t,{recursive:!0,force:!0}),s(`\u{1F9F9} \u6E05\u7406\u8F93\u51FA\u76EE\u5F55: ${C.relative(process.cwd(),t)}`))}catch(o){s(`\u26A0\uFE0F \u6E05\u7406\u8F93\u51FA\u76EE\u5F55\u5931\u8D25: ${t}`,o)}}function de(e){let{entry:t="src/pages/*/main.{ts,js}",exclude:s=[],pageConfigs:o={}}=e,n=B(!1),i=new Set,f=Y.glob.sync(t,{cwd:process.cwd()}),a=G(f,t,s,n);if(a.length===0)throw new Error(`\u672A\u627E\u5230\u5339\u914D\u7684\u5165\u53E3\u6587\u4EF6: ${t}`);try{for(let r of a){let u={pageName:r.name,filePath:r.file,relativePath:C.relative(process.cwd(),r.file)},l=k(o,u,n),d=(l==null?void 0:l.strategy)||"default";i.add(d)}return Array.from(i).sort()}catch(r){return n("\u83B7\u53D6\u53EF\u7528\u7B56\u7565\u5931\u8D25:",r),["default"]}}var X,Y,C,S,W=D(()=>{"use strict";w();X=require("vite"),Y=require("glob"),C=P(require("path")),S=P(require("fs"));J();K();Q()});var te={};A(te,{hasCustomConfig:()=>ye,loadUserConfig:()=>he});function ye(){for(let e of ee){let t=T.resolve(process.cwd(),e);if(_.existsSync(t))return!0}return!1}async function he(e){let t=await we();if(t){let s=t(e);return s||{}}return null}async function $e(e){if(e.endsWith(".ts"))try{let t=await _.promises.readFile(e,"utf-8"),o=await(await import("esbuild")).transform(t,{loader:"ts",format:"cjs",target:"node16",sourcemap:!1}),n=new U.Module(e);return n.filename=e,n.paths=U.Module._nodeModulePaths(T.dirname(e)),n._compile(o.code,e),n.exports}catch(t){console.warn("esbuild \u8F6C\u8BD1\u5931\u8D25\uFF0C\u5C1D\u8BD5\u7B80\u5355\u8F6C\u6362:",t);let o=(await _.promises.readFile(e,"utf-8")).replace(/export\s+default\s+/,"module.exports = ").replace(/import\s+.*?from\s+['"][^'"]*['"];?\s*/g,"").replace(/:\s*[^=,})\]]+/g,""),n=new U.Module(e);return n.filename=e,n.paths=U.Module._nodeModulePaths(T.dirname(e)),n._compile(o,e),n.exports}if(e.endsWith(".js")||e.endsWith(".mjs"))return import(`${(0,Z.pathToFileURL)(e).href}?t=${Date.now()}`);throw new Error(`\u4E0D\u652F\u6301\u7684\u914D\u7F6E\u6587\u4EF6\u7C7B\u578B: ${e}`)}async function we(){let e=process.cwd();for(let t of ee){let s=T.resolve(e,t);if(_.existsSync(s))try{let o=await $e(s),n=o.default||o;if(typeof n=="function")return n;console.warn(`\u914D\u7F6E\u6587\u4EF6 ${t} \u5FC5\u987B\u9ED8\u8BA4\u5BFC\u51FA\u4E00\u4E2A\u51FD\u6570`)}catch(o){t.endsWith(".ts")?(console.error(`\u52A0\u8F7DTypeScript\u914D\u7F6E\u6587\u4EF6 ${t} \u5931\u8D25:`,o),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 ${t} \u5931\u8D25:`,o)}}return null}var _,T,Z,U,ee,se=D(()=>{"use strict";w();_=P(require("fs")),T=P(require("path")),Z=require("url"),U=require("module"),ee=["multipage.config.js","multipage.config.mjs","multipage.config.ts"]});var ne={};A(ne,{DEFAULT_CONFIG:()=>F,isEmptyConfig:()=>xe,mergeWithDefaults:()=>be});function be(e){return e?{entry:e.entry??F.entry,exclude:e.exclude??F.exclude,template:e.template??F.template,placeholder:e.placeholder??F.placeholder,debug:e.debug??F.debug,strategies:e.strategies??F.strategies,pageConfigs:e.pageConfigs??F.pageConfigs,__forceBuildStrategy:e.__forceBuildStrategy}:{...F}}function xe(e){if(Object.keys(e).length===0)return!0;let t=e.entry&&e.entry!==F.entry,s=e.strategies&&Object.keys(e.strategies).length>0,o=e.pageConfigs&&(typeof e.pageConfigs=="function"||Object.keys(e.pageConfigs).length>0);return!t&&!s&&!o}var F,oe=D(()=>{"use strict";w();F={entry:"src/pages/**/*.{ts,js}",exclude:[],template:"index.html",placeholder:"{{ENTRY_FILE}}",debug:!1,strategies:{default:{}},pageConfigs:{}}});var De={};A(De,{buildAll:()=>ie});module.exports=ge(De);w();var re=require("child_process"),m=P(require("fs")),y=P(require("path")),V=P(require("glob"));W();function ve(){let e=process.argv.slice(2),t=[],s=!1,o,n;for(let i=0;i<e.length;i++){let f=e[i];f==="--debug"?s=!0:f==="--cwd"?o=e[++i]:f==="--strategy"?n=e[++i].split(",").map(r=>r.trim()):f==="--help"||f==="-h"?(console.log(`
3
+ \u4F7F\u7528\u65B9\u6CD5: vite-mp [\u9009\u9879]
577
4
 
578
5
  \u9009\u9879:
579
- --debug \u542F\u7528\u8C03\u8BD5\u6A21\u5F0F
580
- --cwd <dir> \u6307\u5B9A\u5DE5\u4F5C\u76EE\u5F55
581
- --help, -h \u663E\u793A\u5E2E\u52A9\u4FE1\u606F
6
+ --debug \u542F\u7528\u8C03\u8BD5\u6A21\u5F0F
7
+ --cwd <dir> \u6307\u5B9A\u5DE5\u4F5C\u76EE\u5F55
8
+ --strategy <list> \u6307\u5B9A\u6784\u5EFA\u7B56\u7565\uFF0C\u652F\u6301\u9017\u53F7\u5206\u9694\u591A\u4E2A\u7B56\u7565
9
+ --help, -h \u663E\u793A\u5E2E\u52A9\u4FE1\u606F
582
10
 
583
11
  \u5176\u4ED6\u6240\u6709\u53C2\u6570\u5C06\u4F20\u9012\u7ED9 vite build \u547D\u4EE4
584
12
 
585
13
  \u793A\u4F8B:
586
- vite-mp
587
- vite-mp --debug
588
- vite-mp --cwd example
589
- vite-mp --mode production --debug
590
- `);
591
- process.exit(0);
592
- } else if (arg !== "build") {
593
- viteBuildArgs.push(arg);
594
- }
595
- }
596
- return { viteBuildArgs, debug, cwd };
597
- }
598
- async function loadViteConfig() {
599
- const { loadUserConfig: loadUserConfig2, hasCustomConfig: hasCustomConfig2 } = await Promise.resolve().then(() => (init_config_loader(), config_loader_exports));
600
- const { mergeWithDefaults: mergeWithDefaults2 } = await Promise.resolve().then(() => (init_defaults(), defaults_exports));
601
- let userConfig = null;
602
- if (hasCustomConfig2()) {
603
- userConfig = await loadUserConfig2({
604
- mode: "production",
605
- command: "build",
606
- isCLI: true
607
- });
608
- } else {
609
- console.log("\u2139\uFE0F \u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u914D\u7F6E");
610
- }
611
- const finalConfig = mergeWithDefaults2(userConfig);
612
- return finalConfig;
613
- }
614
- function buildStrategy(strategy, viteBuildArgs, debug) {
615
- return new Promise((resolve4) => {
616
- var _a;
617
- const log = debug ? console.log.bind(console, `[${strategy}]`) : () => {
618
- };
619
- log(`\u5F00\u59CB\u6784\u5EFA\u7B56\u7565: ${strategy}`);
620
- const env = {
621
- ...process.env,
622
- VITE_BUILD_STRATEGY: strategy
623
- };
624
- const args = ["build", ...viteBuildArgs];
625
- log(`\u6267\u884C\u547D\u4EE4: npx vite ${args.join(" ")}`);
626
- const child = (0, import_node_child_process.spawn)("npx", ["vite", ...args], {
627
- stdio: debug ? "inherit" : "pipe",
628
- env,
629
- cwd: process.cwd()
630
- });
631
- let errorOutput = "";
632
- if (!debug) {
633
- (_a = child.stderr) == null ? void 0 : _a.on("data", (data) => {
634
- errorOutput += data.toString();
635
- });
636
- }
637
- child.on("close", (code) => {
638
- const success = code === 0;
639
- const actualOutputDir = getViteOutputDirectory(viteBuildArgs);
640
- if (success) {
641
- log(`\u2705 \u7B56\u7565 ${strategy} \u6784\u5EFA\u6210\u529F`);
642
- try {
643
- if (fs3.existsSync(actualOutputDir)) {
644
- const files = fs3.readdirSync(actualOutputDir);
645
- for (const file of files) {
646
- if (file.startsWith(".temp.mp.") && file.endsWith(".html")) {
647
- const oldPath = path4.resolve(actualOutputDir, file);
648
- const name = file.replace(/^\.temp\.mp\./, "").replace(/\.html$/, "");
649
- const newName = `${name}.html`;
650
- const newPath = path4.resolve(actualOutputDir, newName);
651
- fs3.renameSync(oldPath, newPath);
652
- log(`\u91CD\u547D\u540DHTML: ${file} -> ${newName}`);
653
- }
654
- }
655
- }
656
- } catch (error) {
657
- log(`\u91CD\u547D\u540DHTML\u6587\u4EF6\u5931\u8D25:`, error);
658
- }
659
- } else {
660
- log(`\u274C \u7B56\u7565 ${strategy} \u6784\u5EFA\u5931\u8D25 (\u9000\u51FA\u7801: ${code})`);
661
- if (!debug && errorOutput) {
662
- console.error(`\u7B56\u7565 ${strategy} \u9519\u8BEF\u8F93\u51FA:`, errorOutput);
663
- }
664
- }
665
- resolve4({
666
- strategy,
667
- success,
668
- error: success ? void 0 : errorOutput || `\u6784\u5EFA\u5931\u8D25\uFF0C\u9000\u51FA\u7801: ${code}`,
669
- outputDir: actualOutputDir
670
- });
671
- });
672
- child.on("error", (error) => {
673
- log(`\u274C \u7B56\u7565 ${strategy} \u6784\u5EFA\u51FA\u9519:`, error.message);
674
- const actualOutputDir = getViteOutputDirectory(viteBuildArgs);
675
- resolve4({
676
- strategy,
677
- success: false,
678
- error: error.message,
679
- outputDir: actualOutputDir
680
- });
681
- });
682
- });
683
- }
684
- async function mergeResults(results, debug) {
685
- const log = debug ? console.log.bind(console, "[merge]") : () => {
686
- };
687
- log("\u5F00\u59CB\u5408\u5E76\u6784\u5EFA\u7ED3\u679C...");
688
- const distDir = path4.resolve(process.cwd(), "dist");
689
- const assetsDir = path4.resolve(distDir, "assets");
690
- if (!fs3.existsSync(assetsDir)) {
691
- fs3.mkdirSync(assetsDir, { recursive: true });
692
- }
693
- const htmlFiles = [];
694
- const strategyInfo = [];
695
- for (const result of results) {
696
- strategyInfo.push({
697
- strategy: result.strategy,
698
- success: result.success,
699
- error: result.error
700
- });
701
- if (!result.success)
702
- continue;
703
- const sourceDir = path4.resolve(distDir, result.strategy);
704
- if (!fs3.existsSync(sourceDir)) {
705
- log(`\u8B66\u544A: \u7B56\u7565\u76EE\u5F55\u4E0D\u5B58\u5728: ${sourceDir}`);
706
- continue;
707
- }
708
- log(`\u5904\u7406\u7B56\u7565: ${result.strategy}`);
709
- const entries = fs3.readdirSync(sourceDir, { withFileTypes: true });
710
- for (const entry of entries) {
711
- const sourcePath = path4.resolve(sourceDir, entry.name);
712
- if (entry.isFile()) {
713
- if (entry.name.endsWith(".html")) {
714
- const targetPath = path4.resolve(distDir, entry.name);
715
- fs3.copyFileSync(sourcePath, targetPath);
716
- htmlFiles.push(entry.name);
717
- log(`\u590D\u5236HTML: ${entry.name} -> dist/${entry.name}`);
718
- } else {
719
- const targetPath = path4.resolve(distDir, entry.name);
720
- fs3.copyFileSync(sourcePath, targetPath);
721
- log(`\u590D\u5236\u6587\u4EF6: ${entry.name} -> dist/${entry.name}`);
722
- }
723
- } else if (entry.isDirectory() && entry.name === "assets") {
724
- const sourceAssetsDir = sourcePath;
725
- const assetEntries = fs3.readdirSync(sourceAssetsDir, { withFileTypes: true });
726
- for (const assetEntry of assetEntries) {
727
- const assetSourcePath = path4.resolve(sourceAssetsDir, assetEntry.name);
728
- const assetTargetPath = path4.resolve(assetsDir, assetEntry.name);
729
- if (assetEntry.isFile()) {
730
- if (fs3.existsSync(assetTargetPath)) {
731
- const sourceContent = fs3.readFileSync(assetSourcePath);
732
- const targetContent = fs3.readFileSync(assetTargetPath);
733
- if (!sourceContent.equals(targetContent)) {
734
- const ext = path4.extname(assetEntry.name);
735
- const baseName = path4.basename(assetEntry.name, ext);
736
- const newName = `${baseName}-${result.strategy}${ext}`;
737
- const newTargetPath = path4.resolve(assetsDir, newName);
738
- fs3.copyFileSync(assetSourcePath, newTargetPath);
739
- log(`\u590D\u5236\u8D44\u6E90(\u91CD\u547D\u540D): ${assetEntry.name} -> assets/${newName}`);
740
- } else {
741
- log(`\u8DF3\u8FC7\u91CD\u590D\u8D44\u6E90: ${assetEntry.name}`);
742
- }
743
- } else {
744
- fs3.copyFileSync(assetSourcePath, assetTargetPath);
745
- log(`\u590D\u5236\u8D44\u6E90: ${assetEntry.name} -> assets/${assetEntry.name}`);
746
- }
747
- } else if (assetEntry.isDirectory()) {
748
- const subTargetDir = path4.resolve(assetsDir, assetEntry.name);
749
- if (!fs3.existsSync(subTargetDir)) {
750
- fs3.mkdirSync(subTargetDir, { recursive: true });
751
- }
752
- fs3.cpSync(assetSourcePath, subTargetDir, { recursive: true });
753
- log(`\u590D\u5236\u8D44\u6E90\u76EE\u5F55: ${assetEntry.name} -> assets/${assetEntry.name}`);
754
- }
755
- }
756
- } else if (entry.isDirectory()) {
757
- const targetDir = path4.resolve(distDir, entry.name);
758
- fs3.cpSync(sourcePath, targetDir, { recursive: true });
759
- log(`\u590D\u5236\u76EE\u5F55: ${entry.name} -> dist/${entry.name}`);
760
- }
761
- }
762
- }
763
- log("\u2705 \u6784\u5EFA\u7ED3\u679C\u5408\u5E76\u5B8C\u6210");
764
- log(`\u{1F4C1} \u751F\u6210\u9875\u9762: ${htmlFiles.join(", ")}`);
765
- log(`\u{1F4E6} \u8D44\u6E90\u76EE\u5F55: dist/assets/`);
766
- log(
767
- `\u{1F527} \u5904\u7406\u7B56\u7565: ${results.filter((r) => r.success).map((r) => r.strategy).join(", ")}`
768
- );
769
- }
770
- async function cleanupTempFiles(debug) {
771
- const log = debug ? console.log.bind(console, "[cleanup]") : () => {
772
- };
773
- log("\u6E05\u7406\u4E34\u65F6HTML\u6587\u4EF6...");
774
- const tempHtmlFiles = glob2.sync(".temp.mp.*.html", { cwd: process.cwd() });
775
- for (const tempFile of tempHtmlFiles) {
776
- const tempPath = path4.resolve(process.cwd(), tempFile);
777
- try {
778
- fs3.unlinkSync(tempPath);
779
- log(`\u5220\u9664\u4E34\u65F6\u6587\u4EF6: ${tempFile}`);
780
- } catch (error) {
781
- log(`\u5220\u9664\u4E34\u65F6\u6587\u4EF6\u5931\u8D25: ${tempFile}`, error);
782
- }
783
- }
784
- if (tempHtmlFiles.length === 0) {
785
- log("\u6CA1\u6709\u627E\u5230\u4E34\u65F6\u6587\u4EF6");
786
- } else {
787
- log(`\u2705 \u6E05\u7406\u4E86 ${tempHtmlFiles.length} \u4E2A\u4E34\u65F6\u6587\u4EF6`);
788
- }
789
- }
790
- async function cleanup(strategies, debug) {
791
- const log = debug ? console.log.bind(console, "[cleanup]") : () => {
792
- };
793
- log("\u6E05\u7406\u4E34\u65F6\u6587\u4EF6...");
794
- const rootTempFiles = glob2.sync(".temp.mp.*.html", { cwd: process.cwd() });
795
- for (const tempFile of rootTempFiles) {
796
- const tempPath = path4.resolve(process.cwd(), tempFile);
797
- try {
798
- fs3.unlinkSync(tempPath);
799
- log(`\u5220\u9664\u6839\u76EE\u5F55\u4E34\u65F6\u6587\u4EF6: ${tempFile}`);
800
- } catch (error) {
801
- log(`\u5220\u9664\u6839\u76EE\u5F55\u4E34\u65F6\u6587\u4EF6\u5931\u8D25: ${tempFile}`, error);
802
- }
803
- }
804
- for (const strategy of strategies) {
805
- const strategyDir = path4.resolve(process.cwd(), "dist", strategy);
806
- if (fs3.existsSync(strategyDir)) {
807
- const strategyTempFiles = glob2.sync("*.mp.temp.html", { cwd: strategyDir });
808
- for (const tempFile of strategyTempFiles) {
809
- const tempPath = path4.resolve(strategyDir, tempFile);
810
- try {
811
- fs3.unlinkSync(tempPath);
812
- log(`\u5220\u9664\u7B56\u7565\u76EE\u5F55\u4E34\u65F6\u6587\u4EF6: ${strategy}/${tempFile}`);
813
- } catch (error) {
814
- log(`\u5220\u9664\u7B56\u7565\u76EE\u5F55\u4E34\u65F6\u6587\u4EF6\u5931\u8D25: ${strategy}/${tempFile}`, error);
815
- }
816
- }
817
- }
818
- }
819
- const distDir = path4.resolve(process.cwd(), "dist");
820
- for (const strategy of strategies) {
821
- const strategyDir = path4.resolve(distDir, strategy);
822
- if (fs3.existsSync(strategyDir)) {
823
- try {
824
- fs3.rmSync(strategyDir, { recursive: true, force: true });
825
- log(`\u5220\u9664\u7B56\u7565\u76EE\u5F55: ${strategy}`);
826
- } catch (error) {
827
- log(`\u5220\u9664\u7B56\u7565\u76EE\u5F55\u5931\u8D25: ${strategy}`, error);
828
- }
829
- }
830
- }
831
- log("\u2705 \u6E05\u7406\u5B8C\u6210");
832
- }
833
- async function main() {
834
- const { viteBuildArgs, debug, cwd } = parseArgs();
835
- const log = debug ? console.log.bind(console, "[main]") : () => {
836
- };
837
- if (cwd) {
838
- const targetDir = path4.resolve(process.cwd(), cwd);
839
- if (!fs3.existsSync(targetDir)) {
840
- console.error(`\u274C \u6307\u5B9A\u7684\u76EE\u5F55\u4E0D\u5B58\u5728: ${targetDir}`);
841
- process.exit(1);
842
- }
843
- process.chdir(targetDir);
844
- log(`\u5207\u6362\u5DE5\u4F5C\u76EE\u5F55\u5230: ${targetDir}`);
845
- }
846
- try {
847
- log("\u{1F680} \u5F00\u59CB\u591A\u7B56\u7565\u6784\u5EFA...");
848
- log("\u{1F4CB} \u52A0\u8F7D\u914D\u7F6E...");
849
- const options = await loadViteConfig();
850
- const { getAvailableStrategies: getAvailableStrategies2 } = await Promise.resolve().then(() => (init_build_config(), build_config_exports));
851
- const strategies = getAvailableStrategies2({
852
- entry: options.entry || "src/pages/*/main.{ts,js}",
853
- exclude: options.exclude || [],
854
- template: options.template || "index.html",
855
- placeholder: options.placeholder || "{{ENTRY_FILE}}",
856
- pageConfigs: options.pageConfigs || {},
857
- strategies: options.strategies || {}
858
- });
859
- if (strategies.length === 0) {
860
- throw new Error("\u672A\u627E\u5230\u4EFB\u4F55\u6784\u5EFA\u7B56\u7565");
861
- }
862
- log(`\u53D1\u73B0 ${strategies.length} \u4E2A\u7B56\u7565: ${strategies.join(", ")}`);
863
- log("\u{1F9F9} \u6E05\u7406\u8F93\u51FA\u76EE\u5F55...");
864
- const { cleanViteOutputDirectory: cleanViteOutputDirectory2 } = await Promise.resolve().then(() => (init_build_config(), build_config_exports));
865
- cleanViteOutputDirectory2(viteBuildArgs);
866
- log("\u{1F528} \u5F00\u59CB\u5E76\u884C\u6784\u5EFA...");
867
- const buildPromises = strategies.map((strategy) => buildStrategy(strategy, viteBuildArgs, debug));
868
- const results = await Promise.all(buildPromises);
869
- const successCount = results.filter((r) => r.success).length;
870
- const failureCount = results.length - successCount;
871
- console.log(`
872
- \u{1F4CA} \u6784\u5EFA\u7ED3\u679C\u7EDF\u8BA1:`);
873
- console.log(`\u2705 \u6210\u529F: ${successCount}`);
874
- console.log(`\u274C \u5931\u8D25: ${failureCount}`);
875
- if (failureCount > 0) {
876
- console.log(`
877
- \u274C \u5931\u8D25\u7684\u7B56\u7565:`);
878
- results.filter((r) => !r.success).forEach((result) => {
879
- console.log(` - ${result.strategy}: ${result.error}`);
880
- });
881
- await cleanupTempFiles(debug);
882
- process.exit(1);
883
- }
884
- log("\u{1F4E6} \u5408\u5E76\u6784\u5EFA\u7ED3\u679C...");
885
- await mergeResults(results, debug);
886
- await cleanup(strategies, debug);
887
- const successfulResults = results.filter((r) => r.success);
888
- const htmlFiles = fs3.readdirSync(path4.resolve(process.cwd(), "dist")).filter((file) => file.endsWith(".html"));
889
- console.log(`
890
- \u{1F389} \u6240\u6709\u7B56\u7565\u6784\u5EFA\u6210\u529F\uFF01`);
891
- console.log(`\u{1F4C1} \u6784\u5EFA\u7ED3\u679C\u4F4D\u4E8E: dist/`);
892
- console.log(`\u{1F310} \u751F\u6210\u7684\u9875\u9762: ${htmlFiles.join(", ")}`);
893
- console.log(`\u{1F4E6} \u6784\u5EFA\u7B56\u7565: ${successfulResults.map((r) => r.strategy).join(", ")}`);
894
- } catch (error) {
895
- console.error("\u274C \u6784\u5EFA\u5931\u8D25:", error instanceof Error ? error.message : error);
896
- process.exit(1);
897
- }
898
- }
899
- if (require.main === module) {
900
- main().catch((error) => {
901
- console.error("\u274C \u672A\u5904\u7406\u7684\u9519\u8BEF:", error);
902
- process.exit(1);
903
- });
904
- }
905
- // Annotate the CommonJS export names for ESM import in node:
906
- 0 && (module.exports = {
907
- buildAll
908
- });
14
+ vite-mp # \u6784\u5EFA\u6240\u6709\u7B56\u7565
15
+ vite-mp --strategy mobile # \u53EA\u6784\u5EFAmobile\u7B56\u7565
16
+ vite-mp --strategy mobile,tablet # \u6784\u5EFAmobile\u548Ctablet\u7B56\u7565
17
+ vite-mp --debug # \u542F\u7528\u8C03\u8BD5\u6A21\u5F0F
18
+ vite-mp --cwd example # \u5728example\u76EE\u5F55\u8FD0\u884C
19
+ vite-mp --mode production --debug # \u4F20\u9012\u989D\u5916\u53C2\u6570\u7ED9vite
20
+ `),process.exit(0)):f!=="build"&&t.push(f)}return{viteBuildArgs:t,debug:s,cwd:o,strategies:n}}async function Ce(){let{loadUserConfig:e,hasCustomConfig:t}=await Promise.resolve().then(()=>(se(),te)),{mergeWithDefaults:s}=await Promise.resolve().then(()=>(oe(),ne)),o=null;return t()?o=await e({mode:"production",command:"build",isCLI:!0}):console.log("\u2139\uFE0F \u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u914D\u7F6E"),s(o)}function Se(e,t,s){return new Promise(o=>{var u;let n=s?console.log.bind(console,`[${e}]`):()=>{};n(`\u5F00\u59CB\u6784\u5EFA\u7B56\u7565: ${e}`);let i={...process.env,VITE_MULTI_PAGE_STRATEGY:e},f=["build",...t];n(`\u6267\u884C\u547D\u4EE4: npx vite ${f.join(" ")}`);let a=(0,re.spawn)("npx",["vite",...f],{stdio:s?"inherit":"pipe",env:i,cwd:process.cwd()}),r="";s||(u=a.stderr)==null||u.on("data",l=>{r+=l.toString()}),a.on("close",l=>{let d=l===0,p=R(t);if(d){n(`\u2705 \u7B56\u7565 ${e} \u6784\u5EFA\u6210\u529F`);try{if(m.existsSync(p)){let $=m.readdirSync(p);for(let g of $)if(g.startsWith(".temp.mp.")&&g.endsWith(".html")){let x=y.resolve(p,g),h=`${g.replace(/^\.temp\.mp\./,"").replace(/\.html$/,"")}.html`,b=y.resolve(p,h);m.renameSync(x,b),n(`\u91CD\u547D\u540DHTML: ${g} -> ${h}`)}}}catch($){n("\u91CD\u547D\u540DHTML\u6587\u4EF6\u5931\u8D25:",$)}}else n(`\u274C \u7B56\u7565 ${e} \u6784\u5EFA\u5931\u8D25 (\u9000\u51FA\u7801: ${l})`),!s&&r&&console.error(`\u7B56\u7565 ${e} \u9519\u8BEF\u8F93\u51FA:`,r);o({strategy:e,success:d,error:d?void 0:r||`\u6784\u5EFA\u5931\u8D25\uFF0C\u9000\u51FA\u7801: ${l}`,outputDir:p})}),a.on("error",l=>{n(`\u274C \u7B56\u7565 ${e} \u6784\u5EFA\u51FA\u9519:`,l.message);let d=R(t);o({strategy:e,success:!1,error:l.message,outputDir:d})})})}async function Fe(e,t){let s=t?console.log.bind(console,"[merge]"):()=>{};s("\u5F00\u59CB\u5408\u5E76\u6784\u5EFA\u7ED3\u679C...");let o=y.resolve(process.cwd(),"dist"),n=y.resolve(o,"assets");m.existsSync(n)||m.mkdirSync(n,{recursive:!0});let i=[],f=[];for(let a of e){if(f.push({strategy:a.strategy,success:a.success,error:a.error}),!a.success)continue;let r=y.resolve(o,a.strategy);if(!m.existsSync(r)){s(`\u8B66\u544A: \u7B56\u7565\u76EE\u5F55\u4E0D\u5B58\u5728: ${r}`);continue}s(`\u5904\u7406\u7B56\u7565: ${a.strategy}`);let u=m.readdirSync(r,{withFileTypes:!0});for(let l of u){let d=y.resolve(r,l.name);if(l.isFile())if(l.name.endsWith(".html")){let p=y.resolve(o,l.name);m.copyFileSync(d,p),i.push(l.name),s(`\u590D\u5236HTML: ${l.name} -> dist/${l.name}`)}else{let p=y.resolve(o,l.name);m.copyFileSync(d,p),s(`\u590D\u5236\u6587\u4EF6: ${l.name} -> dist/${l.name}`)}else if(l.isDirectory()&&l.name==="assets"){let p=d,$=m.readdirSync(p,{withFileTypes:!0});for(let g of $){let x=y.resolve(p,g.name),c=y.resolve(n,g.name);if(g.isFile())if(m.existsSync(c)){let h=m.readFileSync(x),b=m.readFileSync(c);if(h.equals(b))s(`\u8DF3\u8FC7\u91CD\u590D\u8D44\u6E90: ${g.name}`);else{let v=y.extname(g.name),j=`${y.basename(g.name,v)}-${a.strategy}${v}`,M=y.resolve(n,j);m.copyFileSync(x,M),s(`\u590D\u5236\u8D44\u6E90(\u91CD\u547D\u540D): ${g.name} -> assets/${j}`)}}else m.copyFileSync(x,c),s(`\u590D\u5236\u8D44\u6E90: ${g.name} -> assets/${g.name}`);else if(g.isDirectory()){let h=y.resolve(n,g.name);m.existsSync(h)||m.mkdirSync(h,{recursive:!0}),m.cpSync(x,h,{recursive:!0}),s(`\u590D\u5236\u8D44\u6E90\u76EE\u5F55: ${g.name} -> assets/${g.name}`)}}}else if(l.isDirectory()){let p=y.resolve(o,l.name);m.cpSync(d,p,{recursive:!0}),s(`\u590D\u5236\u76EE\u5F55: ${l.name} -> dist/${l.name}`)}}}s("\u2705 \u6784\u5EFA\u7ED3\u679C\u5408\u5E76\u5B8C\u6210"),s(`\u{1F4C1} \u751F\u6210\u9875\u9762: ${i.join(", ")}`),s("\u{1F4E6} \u8D44\u6E90\u76EE\u5F55: dist/assets/"),s(`\u{1F527} \u5904\u7406\u7B56\u7565: ${e.filter(a=>a.success).map(a=>a.strategy).join(", ")}`)}async function Pe(e){let t=e?console.log.bind(console,"[cleanup]"):()=>{};t("\u6E05\u7406\u4E34\u65F6HTML\u6587\u4EF6...");let s=V.sync(".temp.mp.*.html",{cwd:process.cwd()});for(let o of s){let n=y.resolve(process.cwd(),o);try{m.unlinkSync(n),t(`\u5220\u9664\u4E34\u65F6\u6587\u4EF6: ${o}`)}catch(i){t(`\u5220\u9664\u4E34\u65F6\u6587\u4EF6\u5931\u8D25: ${o}`,i)}}s.length===0?t("\u6CA1\u6709\u627E\u5230\u4E34\u65F6\u6587\u4EF6"):t(`\u2705 \u6E05\u7406\u4E86 ${s.length} \u4E2A\u4E34\u65F6\u6587\u4EF6`)}async function Oe(e,t){let s=t?console.log.bind(console,"[cleanup]"):()=>{};s("\u6E05\u7406\u4E34\u65F6\u6587\u4EF6...");let o=V.sync(".temp.mp.*.html",{cwd:process.cwd()});for(let i of o){let f=y.resolve(process.cwd(),i);try{m.unlinkSync(f),s(`\u5220\u9664\u6839\u76EE\u5F55\u4E34\u65F6\u6587\u4EF6: ${i}`)}catch(a){s(`\u5220\u9664\u6839\u76EE\u5F55\u4E34\u65F6\u6587\u4EF6\u5931\u8D25: ${i}`,a)}}for(let i of e){let f=y.resolve(process.cwd(),"dist",i);if(m.existsSync(f)){let a=V.sync("*.mp.temp.html",{cwd:f});for(let r of a){let u=y.resolve(f,r);try{m.unlinkSync(u),s(`\u5220\u9664\u7B56\u7565\u76EE\u5F55\u4E34\u65F6\u6587\u4EF6: ${i}/${r}`)}catch(l){s(`\u5220\u9664\u7B56\u7565\u76EE\u5F55\u4E34\u65F6\u6587\u4EF6\u5931\u8D25: ${i}/${r}`,l)}}}}let n=y.resolve(process.cwd(),"dist");for(let i of e){let f=y.resolve(n,i);if(m.existsSync(f))try{m.rmSync(f,{recursive:!0,force:!0}),s(`\u5220\u9664\u7B56\u7565\u76EE\u5F55: ${i}`)}catch(a){s(`\u5220\u9664\u7B56\u7565\u76EE\u5F55\u5931\u8D25: ${i}`,a)}}s("\u2705 \u6E05\u7406\u5B8C\u6210")}async function ie(){let{viteBuildArgs:e,debug:t,cwd:s,strategies:o}=ve(),n=t?console.log.bind(console,"[main]"):()=>{};if(s){let i=y.resolve(process.cwd(),s);m.existsSync(i)||(console.error(`\u274C \u6307\u5B9A\u7684\u76EE\u5F55\u4E0D\u5B58\u5728: ${i}`),process.exit(1)),process.chdir(i),n(`\u5207\u6362\u5DE5\u4F5C\u76EE\u5F55\u5230: ${i}`)}try{n("\u{1F680} \u5F00\u59CB\u591A\u7B56\u7565\u6784\u5EFA..."),n("\u{1F4CB} \u52A0\u8F7D\u914D\u7F6E...");let i=await Ce(),{getAvailableStrategies:f}=await Promise.resolve().then(()=>(W(),q)),a=f({entry:i.entry||"src/pages/*/main.{ts,js}",exclude:i.exclude||[],template:i.template||"index.html",placeholder:i.placeholder||"{{ENTRY_FILE}}",pageConfigs:i.pageConfigs||{},strategies:i.strategies||{}});if(a.length===0)throw new Error("\u672A\u627E\u5230\u4EFB\u4F55\u6784\u5EFA\u7B56\u7565");let r;if(o&&o.length>0){let c=o.filter(h=>!a.includes(h));if(c.length>0)throw new Error(`\u6307\u5B9A\u7684\u7B56\u7565\u4E0D\u5B58\u5728: ${c.join(", ")}
21
+ \u53EF\u7528\u7B56\u7565: ${a.join(", ")}`);r=o,n(`\u4F7F\u7528\u6307\u5B9A\u7684\u7B56\u7565: ${r.join(", ")}`)}else r=a,n(`\u6784\u5EFA\u6240\u6709\u53EF\u7528\u7B56\u7565: ${r.join(", ")}`);n("\u{1F9F9} \u6E05\u7406\u8F93\u51FA\u76EE\u5F55...");let{cleanViteOutputDirectory:u}=await Promise.resolve().then(()=>(W(),q));u(e),n("\u{1F528} \u5F00\u59CB\u5E76\u884C\u6784\u5EFA...");let l=r.map(c=>Se(c,e,t)),d=await Promise.all(l),p=d.filter(c=>c.success).length,$=d.length-p;console.log(`
22
+ \u{1F4CA} \u6784\u5EFA\u7ED3\u679C\u7EDF\u8BA1:`),console.log(`\u2705 \u6210\u529F: ${p}`),console.log(`\u274C \u5931\u8D25: ${$}`),$>0&&(console.log(`
23
+ \u274C \u5931\u8D25\u7684\u7B56\u7565:`),d.filter(c=>!c.success).forEach(c=>{console.log(` - ${c.strategy}: ${c.error}`)}),await Pe(t),process.exit(1)),n("\u{1F4E6} \u5408\u5E76\u6784\u5EFA\u7ED3\u679C..."),await Fe(d,t),await Oe(r,t);let g=d.filter(c=>c.success),x=m.readdirSync(y.resolve(process.cwd(),"dist")).filter(c=>c.endsWith(".html"));console.log(`
24
+ \u{1F389} \u6240\u6709\u7B56\u7565\u6784\u5EFA\u6210\u529F\uFF01`),console.log("\u{1F4C1} \u6784\u5EFA\u7ED3\u679C\u4F4D\u4E8E: dist/"),console.log(`\u{1F310} \u751F\u6210\u7684\u9875\u9762: ${x.join(", ")}`),console.log(`\u{1F4E6} \u6784\u5EFA\u7B56\u7565: ${g.map(c=>c.strategy).join(", ")}`)}catch(i){console.error("\u274C \u6784\u5EFA\u5931\u8D25:",i instanceof Error?i.message:i),process.exit(1)}}require.main===module&&ie().catch(e=>{console.error("\u274C \u672A\u5904\u7406\u7684\u9519\u8BEF:",e),process.exit(1)});0&&(module.exports={buildAll});