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