@dcf-micro/vite-config 5.5.9

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.
@@ -0,0 +1,103 @@
1
+ import * as vite from 'vite';
2
+ import { ConfigEnv, UserConfig, PluginOption } from 'vite';
3
+ import { PluginVisualizerOptions } from 'rollup-plugin-visualizer';
4
+ export { visualizer as viteVisualizerPlugin } from 'rollup-plugin-visualizer';
5
+ import { PluginOptions } from 'vite-plugin-dts';
6
+ export { default as viteDtsPlugin } from 'vite-plugin-dts';
7
+ import { Options } from 'vite-plugin-pwa';
8
+ export { default as viteCompressPlugin } from 'vite-plugin-compression';
9
+ export { createHtmlPlugin as viteHtmlPlugin } from 'vite-plugin-html';
10
+
11
+ interface IImportMap {
12
+ imports?: Record<string, string>;
13
+ scopes?: {
14
+ [scope: string]: Record<string, string>;
15
+ };
16
+ }
17
+ interface PrintPluginOptions {
18
+ infoMap?: Record<string, string | undefined>;
19
+ }
20
+ interface NitroMockPluginOptions {
21
+ mockServerPackage?: string;
22
+ port?: number;
23
+ verbose?: boolean;
24
+ }
25
+ interface ArchiverPluginOptions {
26
+ name?: string;
27
+ outputDir?: string;
28
+ }
29
+ interface ImportmapPluginOptions {
30
+ defaultProvider?: 'esm.sh' | 'jspm.io';
31
+ importmap?: Array<{
32
+ name: string;
33
+ range?: string;
34
+ }>;
35
+ inputMap?: IImportMap;
36
+ }
37
+ interface CommonPluginOptions {
38
+ devtools?: boolean;
39
+ env?: Record<string, any>;
40
+ injectMetadata?: boolean;
41
+ isBuild?: boolean;
42
+ mode?: string;
43
+ visualizer?: boolean | PluginVisualizerOptions;
44
+ }
45
+ interface ApplicationPluginOptions extends CommonPluginOptions {
46
+ archiver?: boolean;
47
+ archiverPluginOptions?: ArchiverPluginOptions;
48
+ compress?: boolean;
49
+ compressTypes?: ('brotli' | 'gzip')[];
50
+ extraAppConfig?: boolean;
51
+ html?: boolean;
52
+ i18n?: boolean;
53
+ importmap?: boolean;
54
+ importmapOptions?: ImportmapPluginOptions;
55
+ injectAppLoading?: boolean;
56
+ injectGlobalScss?: boolean;
57
+ license?: boolean;
58
+ nitroMock?: boolean;
59
+ nitroMockOptions?: NitroMockPluginOptions;
60
+ print?: boolean;
61
+ printInfoMap?: PrintPluginOptions['infoMap'];
62
+ pwa?: boolean;
63
+ pwaOptions?: Partial<Options>;
64
+ vxeTableLazyImport?: boolean;
65
+ }
66
+ interface LibraryPluginOptions extends CommonPluginOptions {
67
+ dts?: boolean | PluginOptions;
68
+ }
69
+ type ApplicationOptions = ApplicationPluginOptions;
70
+ type LibraryOptions = LibraryPluginOptions;
71
+ type DefineApplicationOptions = (config?: ConfigEnv) => Promise<{
72
+ application?: ApplicationOptions;
73
+ vite?: UserConfig;
74
+ }>;
75
+ type DefineLibraryOptions = (config?: ConfigEnv) => Promise<{
76
+ library?: LibraryOptions;
77
+ vite?: UserConfig;
78
+ }>;
79
+ type DefineConfig = DefineApplicationOptions | DefineLibraryOptions;
80
+
81
+ declare function defineApplicationConfig(userConfigPromise?: DefineApplicationOptions): vite.UserConfigFnPromise;
82
+
83
+ declare function defineLibraryConfig(userConfigPromise?: DefineLibraryOptions): vite.UserConfigFnPromise;
84
+
85
+ declare function defineConfig(userConfigPromise?: DefineConfig, type?: 'application' | 'auto' | 'library'): vite.UserConfigFnPromise;
86
+
87
+ declare const getDefaultPwaOptions: (name: string) => Partial<Options>;
88
+ declare const defaultImportmapOptions: ImportmapPluginOptions;
89
+
90
+ declare const viteArchiverPlugin: (options?: ArchiverPluginOptions) => PluginOption;
91
+
92
+ declare function viteVxeTableImportsPlugin(): Promise<PluginOption>;
93
+
94
+ declare function loadApplicationPlugins(options: ApplicationPluginOptions): Promise<PluginOption[]>;
95
+ declare function loadLibraryPlugins(options: LibraryPluginOptions): Promise<PluginOption[]>;
96
+
97
+ declare function loadAndConvertEnv(match?: string, confFiles?: string[]): Promise<Partial<ApplicationPluginOptions> & {
98
+ appTitle: string;
99
+ base: string;
100
+ port: number;
101
+ }>;
102
+
103
+ export { defaultImportmapOptions, defineApplicationConfig, defineConfig, defineLibraryConfig, getDefaultPwaOptions, loadAndConvertEnv, loadApplicationPlugins, loadLibraryPlugins, viteArchiverPlugin, viteVxeTableImportsPlugin };
@@ -0,0 +1,103 @@
1
+ import * as vite from 'vite';
2
+ import { ConfigEnv, UserConfig, PluginOption } from 'vite';
3
+ import { PluginVisualizerOptions } from 'rollup-plugin-visualizer';
4
+ export { visualizer as viteVisualizerPlugin } from 'rollup-plugin-visualizer';
5
+ import { PluginOptions } from 'vite-plugin-dts';
6
+ export { default as viteDtsPlugin } from 'vite-plugin-dts';
7
+ import { Options } from 'vite-plugin-pwa';
8
+ export { default as viteCompressPlugin } from 'vite-plugin-compression';
9
+ export { createHtmlPlugin as viteHtmlPlugin } from 'vite-plugin-html';
10
+
11
+ interface IImportMap {
12
+ imports?: Record<string, string>;
13
+ scopes?: {
14
+ [scope: string]: Record<string, string>;
15
+ };
16
+ }
17
+ interface PrintPluginOptions {
18
+ infoMap?: Record<string, string | undefined>;
19
+ }
20
+ interface NitroMockPluginOptions {
21
+ mockServerPackage?: string;
22
+ port?: number;
23
+ verbose?: boolean;
24
+ }
25
+ interface ArchiverPluginOptions {
26
+ name?: string;
27
+ outputDir?: string;
28
+ }
29
+ interface ImportmapPluginOptions {
30
+ defaultProvider?: 'esm.sh' | 'jspm.io';
31
+ importmap?: Array<{
32
+ name: string;
33
+ range?: string;
34
+ }>;
35
+ inputMap?: IImportMap;
36
+ }
37
+ interface CommonPluginOptions {
38
+ devtools?: boolean;
39
+ env?: Record<string, any>;
40
+ injectMetadata?: boolean;
41
+ isBuild?: boolean;
42
+ mode?: string;
43
+ visualizer?: boolean | PluginVisualizerOptions;
44
+ }
45
+ interface ApplicationPluginOptions extends CommonPluginOptions {
46
+ archiver?: boolean;
47
+ archiverPluginOptions?: ArchiverPluginOptions;
48
+ compress?: boolean;
49
+ compressTypes?: ('brotli' | 'gzip')[];
50
+ extraAppConfig?: boolean;
51
+ html?: boolean;
52
+ i18n?: boolean;
53
+ importmap?: boolean;
54
+ importmapOptions?: ImportmapPluginOptions;
55
+ injectAppLoading?: boolean;
56
+ injectGlobalScss?: boolean;
57
+ license?: boolean;
58
+ nitroMock?: boolean;
59
+ nitroMockOptions?: NitroMockPluginOptions;
60
+ print?: boolean;
61
+ printInfoMap?: PrintPluginOptions['infoMap'];
62
+ pwa?: boolean;
63
+ pwaOptions?: Partial<Options>;
64
+ vxeTableLazyImport?: boolean;
65
+ }
66
+ interface LibraryPluginOptions extends CommonPluginOptions {
67
+ dts?: boolean | PluginOptions;
68
+ }
69
+ type ApplicationOptions = ApplicationPluginOptions;
70
+ type LibraryOptions = LibraryPluginOptions;
71
+ type DefineApplicationOptions = (config?: ConfigEnv) => Promise<{
72
+ application?: ApplicationOptions;
73
+ vite?: UserConfig;
74
+ }>;
75
+ type DefineLibraryOptions = (config?: ConfigEnv) => Promise<{
76
+ library?: LibraryOptions;
77
+ vite?: UserConfig;
78
+ }>;
79
+ type DefineConfig = DefineApplicationOptions | DefineLibraryOptions;
80
+
81
+ declare function defineApplicationConfig(userConfigPromise?: DefineApplicationOptions): vite.UserConfigFnPromise;
82
+
83
+ declare function defineLibraryConfig(userConfigPromise?: DefineLibraryOptions): vite.UserConfigFnPromise;
84
+
85
+ declare function defineConfig(userConfigPromise?: DefineConfig, type?: 'application' | 'auto' | 'library'): vite.UserConfigFnPromise;
86
+
87
+ declare const getDefaultPwaOptions: (name: string) => Partial<Options>;
88
+ declare const defaultImportmapOptions: ImportmapPluginOptions;
89
+
90
+ declare const viteArchiverPlugin: (options?: ArchiverPluginOptions) => PluginOption;
91
+
92
+ declare function viteVxeTableImportsPlugin(): Promise<PluginOption>;
93
+
94
+ declare function loadApplicationPlugins(options: ApplicationPluginOptions): Promise<PluginOption[]>;
95
+ declare function loadLibraryPlugins(options: LibraryPluginOptions): Promise<PluginOption[]>;
96
+
97
+ declare function loadAndConvertEnv(match?: string, confFiles?: string[]): Promise<Partial<ApplicationPluginOptions> & {
98
+ appTitle: string;
99
+ base: string;
100
+ port: number;
101
+ }>;
102
+
103
+ export { defaultImportmapOptions, defineApplicationConfig, defineConfig, defineLibraryConfig, getDefaultPwaOptions, loadAndConvertEnv, loadApplicationPlugins, loadLibraryPlugins, viteArchiverPlugin, viteVxeTableImportsPlugin };
package/dist/index.mjs ADDED
@@ -0,0 +1,1100 @@
1
+ import fs, { existsSync } from 'node:fs';
2
+ import path, { join, relative } from 'node:path';
3
+ import { readPackageJSON, generatorContentHash, colors, dateUtil, getPackages, findMonorepoRoot, getPackage, consola, fs as fs$1 } from '@dcf-micro/utils-node';
4
+ import { NodePackageImporter } from 'sass';
5
+ import { defineConfig as defineConfig$1, loadEnv as loadEnv$1, mergeConfig } from 'vite';
6
+ import { constants } from 'zlib';
7
+ import viteVueI18nPlugin from '@intlify/unplugin-vue-i18n/vite';
8
+ import viteVue from '@vitejs/plugin-vue';
9
+ import viteVueJsx from '@vitejs/plugin-vue-jsx';
10
+ import { visualizer } from 'rollup-plugin-visualizer';
11
+ export { visualizer as viteVisualizerPlugin } from 'rollup-plugin-visualizer';
12
+ import viteCompressPlugin from 'vite-plugin-compression';
13
+ export { default as viteCompressPlugin } from 'vite-plugin-compression';
14
+ import viteDtsPlugin from 'vite-plugin-dts';
15
+ export { default as viteDtsPlugin } from 'vite-plugin-dts';
16
+ import { createHtmlPlugin } from 'vite-plugin-html';
17
+ export { createHtmlPlugin as viteHtmlPlugin } from 'vite-plugin-html';
18
+ import { VitePWA } from 'vite-plugin-pwa';
19
+ import viteVueDevTools from 'vite-plugin-vue-devtools';
20
+ import fsp from 'node:fs/promises';
21
+ import archiver from 'archiver';
22
+ import { Generator } from '@jspm/generator';
23
+ import { load } from 'cheerio';
24
+ import { minify } from 'html-minifier-terser';
25
+ import { fileURLToPath } from 'node:url';
26
+ import { readWorkspaceManifest } from '@pnpm/workspace.read-manifest';
27
+ import { EOL } from 'node:os';
28
+ import getPort from 'get-port';
29
+ import { createNitro, createDevServer, prepare, build } from 'nitropack';
30
+ import { lazyImport, VxeResolver } from 'vite-plugin-lazy-import';
31
+ import dotenv from 'dotenv';
32
+
33
+ const isDevelopment = process.env.NODE_ENV === "development";
34
+ const getDefaultPwaOptions = (name) => ({
35
+ manifest: {
36
+ description: "Vben Admin is a modern admin dashboard template based on Vue 3. ",
37
+ icons: [
38
+ {
39
+ sizes: "192x192",
40
+ src: "https://unpkg.com/@vbenjs/static-source@0.1.7/source/pwa-icon-192.png",
41
+ type: "image/png"
42
+ },
43
+ {
44
+ sizes: "512x512",
45
+ src: "https://unpkg.com/@vbenjs/static-source@0.1.7/source/pwa-icon-512.png",
46
+ type: "image/png"
47
+ }
48
+ ],
49
+ name: `${name}${isDevelopment ? " dev" : ""}`,
50
+ short_name: `${name}${isDevelopment ? " dev" : ""}`
51
+ }
52
+ });
53
+ const defaultImportmapOptions = {
54
+ // 通过 Importmap CDN 方式引入,
55
+ // 目前只有esm.sh源兼容性好一点,jspm.io对于 esm 入口要求高
56
+ defaultProvider: "esm.sh",
57
+ importmap: [
58
+ { name: "vue" },
59
+ { name: "pinia" },
60
+ { name: "vue-router" },
61
+ // { name: 'vue-i18n' },
62
+ { name: "dayjs" },
63
+ { name: "vue-demi" }
64
+ ]
65
+ };
66
+
67
+ const viteArchiverPlugin = (options = {}) => {
68
+ return {
69
+ apply: "build",
70
+ closeBundle: {
71
+ handler() {
72
+ const { name = "dist", outputDir = "." } = options;
73
+ setTimeout(async () => {
74
+ const folderToZip = "dist";
75
+ const zipOutputDir = join(process.cwd(), outputDir);
76
+ const zipOutputPath = join(zipOutputDir, `${name}.zip`);
77
+ try {
78
+ await fsp.mkdir(zipOutputDir, { recursive: true });
79
+ } catch {
80
+ }
81
+ try {
82
+ await zipFolder(folderToZip, zipOutputPath);
83
+ console.log(`Folder has been zipped to: ${zipOutputPath}`);
84
+ } catch (error) {
85
+ console.error("Error zipping folder:", error);
86
+ }
87
+ }, 0);
88
+ },
89
+ order: "post"
90
+ },
91
+ enforce: "post",
92
+ name: "vite:archiver"
93
+ };
94
+ };
95
+ async function zipFolder(folderPath, outputPath) {
96
+ return new Promise((resolve, reject) => {
97
+ const output = fs.createWriteStream(outputPath);
98
+ const archive = archiver("zip", {
99
+ zlib: { level: 9 }
100
+ // 设置压缩级别为 9 以实现最高压缩率
101
+ });
102
+ output.on("close", () => {
103
+ console.log(
104
+ `ZIP file created: ${outputPath} (${archive.pointer()} total bytes)`
105
+ );
106
+ resolve();
107
+ });
108
+ archive.on("error", (err) => {
109
+ reject(err);
110
+ });
111
+ archive.pipe(output);
112
+ archive.directory(folderPath, false);
113
+ archive.finalize();
114
+ });
115
+ }
116
+
117
+ const GLOBAL_CONFIG_FILE_NAME = "_app.config.js";
118
+ const DEFAULT_VBEN_ADMIN_PRO_APP_CONF = "_VBEN_ADMIN_PRO_APP_CONF_";
119
+ async function viteExtraAppConfigPlugin({
120
+ isBuild,
121
+ root,
122
+ env
123
+ }) {
124
+ let publicPath;
125
+ let source;
126
+ const { version = "" } = await readPackageJSON(root);
127
+ return {
128
+ async configResolved(config) {
129
+ publicPath = ensureTrailingSlash(config.base);
130
+ source = await getConfigSource(env);
131
+ },
132
+ async generateBundle() {
133
+ try {
134
+ this.emitFile({
135
+ fileName: GLOBAL_CONFIG_FILE_NAME,
136
+ source,
137
+ type: "asset"
138
+ });
139
+ console.log(colors.cyan(`\u2728configuration file is build successfully!`));
140
+ } catch (error) {
141
+ console.log(
142
+ colors.red(
143
+ `configuration file configuration file failed to package:
144
+ ${error}`
145
+ )
146
+ );
147
+ }
148
+ },
149
+ name: "vite:extra-app-config",
150
+ async transformIndexHtml(html) {
151
+ const hash = `v=${version}-${generatorContentHash(source, 8)}`;
152
+ const appConfigSrc = `${publicPath}${GLOBAL_CONFIG_FILE_NAME}?${hash}`;
153
+ return {
154
+ html,
155
+ tags: [{ attrs: { src: appConfigSrc }, tag: "script" }]
156
+ };
157
+ }
158
+ };
159
+ }
160
+ async function getConfigSource(env) {
161
+ const config = {};
162
+ Object.keys(env).forEach((key) => {
163
+ if (key.startsWith("VITE_GLOB_")) {
164
+ config[key] = env[key];
165
+ }
166
+ });
167
+ const variableName = env.VITE_APP_CONF_NAME || DEFAULT_VBEN_ADMIN_PRO_APP_CONF;
168
+ const windowVariable = `window.${variableName}`;
169
+ const source = `
170
+ if (!Object.prototype.hasOwnProperty.call(window, "${variableName}")) {
171
+ ${windowVariable}=${JSON.stringify(config)};
172
+ Object.freeze(${windowVariable});
173
+ Object.defineProperty(window, "${variableName}", {
174
+ configurable: false,
175
+ writable: false,
176
+ });
177
+ }
178
+ `.replaceAll(/\s/g, "");
179
+ return source;
180
+ }
181
+ function ensureTrailingSlash(path) {
182
+ return path.endsWith("/") ? path : `${path}/`;
183
+ }
184
+
185
+ const DEFAULT_PROVIDER = "jspm.io";
186
+ async function getShimsUrl(provide) {
187
+ const version = "1.10.0";
188
+ const shimsSubpath = `dist/es-module-shims.js`;
189
+ const providerShimsMap = {
190
+ "esm.sh": `https://esm.sh/es-module-shims@${version}/${shimsSubpath}`,
191
+ // unpkg: `https://unpkg.com/es-module-shims@${version}/${shimsSubpath}`,
192
+ jsdelivr: `https://cdn.jsdelivr.net/npm/es-module-shims@${version}/${shimsSubpath}`,
193
+ // 下面两个CDN不稳定,暂时不用
194
+ "jspm.io": `https://ga.jspm.io/npm:es-module-shims@${version}/${shimsSubpath}`
195
+ };
196
+ return providerShimsMap[provide] || providerShimsMap[DEFAULT_PROVIDER];
197
+ }
198
+ let generator;
199
+ async function viteImportMapPlugin(pluginOptions) {
200
+ const { importmap } = pluginOptions || {};
201
+ let isSSR = false;
202
+ let isBuild = false;
203
+ let installed = false;
204
+ let installError = null;
205
+ const options = Object.assign(
206
+ {},
207
+ {
208
+ debug: false,
209
+ defaultProvider: "jspm.io",
210
+ env: ["production", "browser", "module"],
211
+ importmap: []
212
+ },
213
+ pluginOptions
214
+ );
215
+ generator = new Generator({
216
+ ...options,
217
+ baseUrl: process.cwd()
218
+ });
219
+ if (options?.debug) {
220
+ (async () => {
221
+ for await (const { message, type } of generator.logStream()) {
222
+ console.log(`${type}: ${message}`);
223
+ }
224
+ })();
225
+ }
226
+ const imports = options.inputMap?.imports ?? {};
227
+ const scopes = options.inputMap?.scopes ?? {};
228
+ const firstLayerKeys = Object.keys(scopes);
229
+ const inputMapScopes = [];
230
+ firstLayerKeys.forEach((key) => {
231
+ inputMapScopes.push(...Object.keys(scopes[key] || {}));
232
+ });
233
+ const inputMapImports = Object.keys(imports);
234
+ const allDepNames = [
235
+ ...importmap?.map((item) => item.name) || [],
236
+ ...inputMapImports,
237
+ ...inputMapScopes
238
+ ];
239
+ const depNames = new Set(allDepNames);
240
+ const installDeps = importmap?.map((item) => ({
241
+ range: item.range,
242
+ target: item.name
243
+ }));
244
+ return [
245
+ {
246
+ async config(_, { command, isSsrBuild }) {
247
+ isBuild = command === "build";
248
+ isSSR = !!isSsrBuild;
249
+ },
250
+ enforce: "pre",
251
+ name: "importmap:external",
252
+ resolveId(id) {
253
+ if (isSSR || !isBuild) {
254
+ return null;
255
+ }
256
+ if (!depNames.has(id)) {
257
+ return null;
258
+ }
259
+ return { external: true, id };
260
+ }
261
+ },
262
+ {
263
+ enforce: "post",
264
+ name: "importmap:install",
265
+ async resolveId() {
266
+ if (isSSR || !isBuild || installed) {
267
+ return null;
268
+ }
269
+ try {
270
+ installed = true;
271
+ await Promise.allSettled(
272
+ (installDeps || []).map((dep) => generator.install(dep))
273
+ );
274
+ } catch (error) {
275
+ installError = error;
276
+ installed = false;
277
+ }
278
+ return null;
279
+ }
280
+ },
281
+ {
282
+ buildEnd() {
283
+ if (!installed && !isSSR) {
284
+ installError && console.error(installError);
285
+ throw new Error("Importmap installation failed.");
286
+ }
287
+ },
288
+ enforce: "post",
289
+ name: "importmap:html",
290
+ transformIndexHtml: {
291
+ async handler(html) {
292
+ if (isSSR || !isBuild) {
293
+ return html;
294
+ }
295
+ const importmapJson = generator.getMap();
296
+ if (!importmapJson) {
297
+ return html;
298
+ }
299
+ const esModuleShimsSrc = await getShimsUrl(
300
+ options.defaultProvider || DEFAULT_PROVIDER
301
+ );
302
+ const resultHtml = await injectShimsToHtml(
303
+ html,
304
+ esModuleShimsSrc || ""
305
+ );
306
+ html = await minify(resultHtml || html, {
307
+ collapseWhitespace: true,
308
+ minifyCSS: true,
309
+ minifyJS: true,
310
+ removeComments: false
311
+ });
312
+ return {
313
+ html,
314
+ tags: [
315
+ {
316
+ attrs: {
317
+ type: "importmap"
318
+ },
319
+ injectTo: "head-prepend",
320
+ tag: "script",
321
+ children: `${JSON.stringify(importmapJson)}`
322
+ }
323
+ ]
324
+ };
325
+ },
326
+ order: "post"
327
+ }
328
+ }
329
+ ];
330
+ }
331
+ async function injectShimsToHtml(html, esModuleShimUrl) {
332
+ const $ = load(html);
333
+ const $script = $(`script[type='module']`);
334
+ if (!$script) {
335
+ return;
336
+ }
337
+ const entry = $script.attr("src");
338
+ $script.removeAttr("type");
339
+ $script.removeAttr("crossorigin");
340
+ $script.removeAttr("src");
341
+ $script.html(`
342
+ if (!HTMLScriptElement.supports || !HTMLScriptElement.supports('importmap')) {
343
+ self.importShim = function () {
344
+ const promise = new Promise((resolve, reject) => {
345
+ document.head.appendChild(
346
+ Object.assign(document.createElement('script'), {
347
+ src: '${esModuleShimUrl}',
348
+ crossorigin: 'anonymous',
349
+ async: true,
350
+ onload() {
351
+ if (!importShim.$proxy) {
352
+ resolve(importShim);
353
+ } else {
354
+ reject(new Error('No globalThis.importShim found:' + esModuleShimUrl));
355
+ }
356
+ },
357
+ onerror(error) {
358
+ reject(error);
359
+ },
360
+ }),
361
+ );
362
+ });
363
+ importShim.$proxy = true;
364
+ return promise.then((importShim) => importShim(...arguments));
365
+ };
366
+ }
367
+
368
+ var modules = ['${entry}'];
369
+ typeof importShim === 'function'
370
+ ? modules.forEach((moduleName) => importShim(moduleName))
371
+ : modules.forEach((moduleName) => import(moduleName));
372
+ `);
373
+ $("body").after($script);
374
+ $("head").remove(`script[type='module']`);
375
+ return $.html();
376
+ }
377
+
378
+ async function viteInjectAppLoadingPlugin(isBuild, env = {}, loadingTemplate = "loading.html") {
379
+ const loadingHtml = await getLoadingRawByHtmlTemplate(loadingTemplate);
380
+ const { version } = await readPackageJSON(process.cwd());
381
+ const envRaw = isBuild ? "prod" : "dev";
382
+ const cacheName = `'${env.VITE_APP_NAMESPACE}-${version}-${envRaw}-preferences-theme'`;
383
+ const injectScript = `
384
+ <script data-app-loading="inject-js">
385
+ var theme = localStorage.getItem(${cacheName});
386
+ document.documentElement.classList.toggle('dark', /dark/.test(theme));
387
+ <\/script>
388
+ `;
389
+ if (!loadingHtml) {
390
+ return;
391
+ }
392
+ return {
393
+ enforce: "pre",
394
+ name: "vite:inject-app-loading",
395
+ transformIndexHtml: {
396
+ handler(html) {
397
+ const re = /<body\s*>/;
398
+ html = html.replace(re, `<body>${injectScript}${loadingHtml}`);
399
+ return html;
400
+ },
401
+ order: "pre"
402
+ }
403
+ };
404
+ }
405
+ async function getLoadingRawByHtmlTemplate(loadingTemplate) {
406
+ let appLoadingPath = join(process.cwd(), loadingTemplate);
407
+ if (!fs.existsSync(appLoadingPath)) {
408
+ const __dirname = fileURLToPath(new URL(".", import.meta.url));
409
+ appLoadingPath = join(__dirname, "./default-loading.html");
410
+ }
411
+ return await fsp.readFile(appLoadingPath, "utf8");
412
+ }
413
+
414
+ function resolvePackageVersion(pkgsMeta, name, value, catalog) {
415
+ if (value.includes("catalog:")) {
416
+ return catalog[name];
417
+ }
418
+ if (value.includes("workspace")) {
419
+ return pkgsMeta[name];
420
+ }
421
+ return value;
422
+ }
423
+ async function resolveMonorepoDependencies() {
424
+ const { packages } = await getPackages();
425
+ const manifest = await readWorkspaceManifest(findMonorepoRoot());
426
+ const catalog = manifest?.catalog || {};
427
+ const resultDevDependencies = {};
428
+ const resultDependencies = {};
429
+ const pkgsMeta = {};
430
+ for (const { packageJson } of packages) {
431
+ pkgsMeta[packageJson.name] = packageJson.version;
432
+ }
433
+ for (const { packageJson } of packages) {
434
+ const { dependencies = {}, devDependencies = {} } = packageJson;
435
+ for (const [key, value] of Object.entries(dependencies)) {
436
+ resultDependencies[key] = resolvePackageVersion(
437
+ pkgsMeta,
438
+ key,
439
+ value,
440
+ catalog
441
+ );
442
+ }
443
+ for (const [key, value] of Object.entries(devDependencies)) {
444
+ resultDevDependencies[key] = resolvePackageVersion(
445
+ pkgsMeta,
446
+ key,
447
+ value,
448
+ catalog
449
+ );
450
+ }
451
+ }
452
+ return {
453
+ dependencies: resultDependencies,
454
+ devDependencies: resultDevDependencies
455
+ };
456
+ }
457
+ async function viteMetadataPlugin(root = process.cwd()) {
458
+ const { author, description, homepage, license, version } = await readPackageJSON(root);
459
+ const buildTime = dateUtil().format("YYYY-MM-DD HH:mm:ss");
460
+ return {
461
+ async config() {
462
+ const { dependencies, devDependencies } = await resolveMonorepoDependencies();
463
+ const isAuthorObject = typeof author === "object";
464
+ const authorName = isAuthorObject ? author.name : author;
465
+ const authorEmail = isAuthorObject ? author.email : null;
466
+ const authorUrl = isAuthorObject ? author.url : null;
467
+ return {
468
+ define: {
469
+ __VBEN_ADMIN_METADATA__: JSON.stringify({
470
+ authorEmail,
471
+ authorName,
472
+ authorUrl,
473
+ buildTime,
474
+ dependencies,
475
+ description,
476
+ devDependencies,
477
+ homepage,
478
+ license,
479
+ version
480
+ }),
481
+ "import.meta.env.VITE_APP_VERSION": JSON.stringify(version)
482
+ }
483
+ };
484
+ },
485
+ enforce: "post",
486
+ name: "vite:inject-metadata"
487
+ };
488
+ }
489
+
490
+ async function viteLicensePlugin(root = process.cwd()) {
491
+ const { version = "" } = await readPackageJSON(root);
492
+ return {
493
+ apply: "build",
494
+ enforce: "post",
495
+ generateBundle: {
496
+ handler: (_options, bundle) => {
497
+ const date = dateUtil().format("YYYY-MM-DD ");
498
+ const copyrightText = `
499
+ /*!
500
+ * Version: ${version}
501
+ * Date Created: ${date}
502
+ */
503
+ `.trim();
504
+ for (const [, fileContent] of Object.entries(bundle)) {
505
+ if (fileContent.type === "chunk" && fileContent.isEntry) {
506
+ const chunkContent = fileContent;
507
+ const content = chunkContent.code;
508
+ const updatedContent = `${copyrightText}${EOL}${content}`;
509
+ fileContent.code = updatedContent;
510
+ }
511
+ }
512
+ },
513
+ order: "post"
514
+ },
515
+ name: "vite:license"
516
+ };
517
+ }
518
+
519
+ const hmrKeyRe = /^runtimeConfig\.|routeRules\./;
520
+ const viteNitroMockPlugin = ({
521
+ mockServerPackage = "",
522
+ port = 5320,
523
+ verbose = true
524
+ } = {}) => {
525
+ return {
526
+ async configureServer(server) {
527
+ if (!mockServerPackage) {
528
+ return;
529
+ }
530
+ const availablePort = await getPort({ port });
531
+ if (availablePort !== port) {
532
+ return;
533
+ }
534
+ const pkg = await getPackage(mockServerPackage);
535
+ if (!pkg) {
536
+ consola.log(
537
+ `Package ${mockServerPackage} not found. Skip mock server.`
538
+ );
539
+ return;
540
+ }
541
+ runNitroServer(pkg.dir, port, verbose);
542
+ const _printUrls = server.printUrls;
543
+ server.printUrls = () => {
544
+ _printUrls();
545
+ consola.log(
546
+ ` ${colors.green("\u279C")} ${colors.bold("Nitro Mock Server")}: ${colors.cyan(`http://localhost:${port}/api`)}`
547
+ );
548
+ };
549
+ },
550
+ enforce: "pre",
551
+ name: "vite:mock-server"
552
+ };
553
+ };
554
+ async function runNitroServer(rootDir, port, verbose) {
555
+ let nitro;
556
+ const reload = async () => {
557
+ if (nitro) {
558
+ consola.info("Restarting dev server...");
559
+ if ("unwatch" in nitro.options._c12) {
560
+ await nitro.options._c12.unwatch();
561
+ }
562
+ await nitro.close();
563
+ }
564
+ nitro = await createNitro(
565
+ {
566
+ dev: true,
567
+ preset: "nitro-dev",
568
+ rootDir
569
+ },
570
+ {
571
+ c12: {
572
+ async onUpdate({ getDiff, newConfig }) {
573
+ const diff = getDiff();
574
+ if (diff.length === 0) {
575
+ return;
576
+ }
577
+ verbose && consola.info(
578
+ `Nitro config updated:
579
+ ${diff.map((entry) => ` ${entry.toString()}`).join("\n")}`
580
+ );
581
+ await (diff.every((e) => hmrKeyRe.test(e.key)) ? nitro.updateConfig(newConfig.config) : reload());
582
+ }
583
+ },
584
+ watch: true
585
+ }
586
+ );
587
+ nitro.hooks.hookOnce("restart", reload);
588
+ const server = createDevServer(nitro);
589
+ await server.listen(port, { showURL: false });
590
+ await prepare(nitro);
591
+ await build(nitro);
592
+ if (verbose) {
593
+ console.log("");
594
+ consola.success(colors.bold(colors.green("Nitro Mock Server started.")));
595
+ }
596
+ };
597
+ return await reload();
598
+ }
599
+
600
+ const vitePrintPlugin = (options = {}) => {
601
+ const { infoMap = {} } = options;
602
+ return {
603
+ configureServer(server) {
604
+ const _printUrls = server.printUrls;
605
+ server.printUrls = () => {
606
+ _printUrls();
607
+ for (const [key, value] of Object.entries(infoMap)) {
608
+ console.log(
609
+ ` ${colors.green("\u279C")} ${colors.bold(key)}: ${colors.cyan(value)}`
610
+ );
611
+ }
612
+ };
613
+ },
614
+ enforce: "pre",
615
+ name: "vite:print-info"
616
+ };
617
+ };
618
+
619
+ async function viteVxeTableImportsPlugin() {
620
+ return [
621
+ lazyImport({
622
+ resolvers: [
623
+ VxeResolver({
624
+ libraryName: "vxe-table"
625
+ }),
626
+ VxeResolver({
627
+ libraryName: "vxe-pc-ui"
628
+ })
629
+ ]
630
+ })
631
+ ];
632
+ }
633
+
634
+ async function loadConditionPlugins(conditionPlugins) {
635
+ const plugins = [];
636
+ for (const conditionPlugin of conditionPlugins) {
637
+ if (conditionPlugin.condition) {
638
+ const realPlugins = await conditionPlugin.plugins();
639
+ plugins.push(...realPlugins);
640
+ }
641
+ }
642
+ return plugins.flat();
643
+ }
644
+ async function loadCommonPlugins(options) {
645
+ const { devtools, injectMetadata, isBuild, visualizer: visualizer$1 } = options;
646
+ return [
647
+ {
648
+ condition: true,
649
+ plugins: () => [
650
+ viteVue({
651
+ script: {
652
+ defineModel: true
653
+ // propsDestructure: true,
654
+ }
655
+ }),
656
+ viteVueJsx()
657
+ ]
658
+ },
659
+ {
660
+ condition: !isBuild && devtools,
661
+ plugins: () => [viteVueDevTools()]
662
+ },
663
+ {
664
+ condition: injectMetadata,
665
+ plugins: async () => [await viteMetadataPlugin()]
666
+ },
667
+ {
668
+ condition: isBuild && !!visualizer$1,
669
+ plugins: () => [visualizer({
670
+ filename: "./node_modules/.cache/visualizer/stats.html",
671
+ gzipSize: true,
672
+ open: true
673
+ })]
674
+ }
675
+ ];
676
+ }
677
+ async function loadApplicationPlugins(options) {
678
+ const isBuild = options.isBuild;
679
+ const env = options.env;
680
+ const {
681
+ archiver,
682
+ archiverPluginOptions,
683
+ compress,
684
+ compressTypes,
685
+ extraAppConfig,
686
+ html,
687
+ i18n,
688
+ importmap,
689
+ importmapOptions,
690
+ injectAppLoading,
691
+ license,
692
+ nitroMock,
693
+ nitroMockOptions,
694
+ print,
695
+ printInfoMap,
696
+ pwa,
697
+ pwaOptions,
698
+ vxeTableLazyImport,
699
+ ...commonOptions
700
+ } = options;
701
+ const commonPlugins = await loadCommonPlugins(commonOptions);
702
+ return await loadConditionPlugins([
703
+ ...commonPlugins,
704
+ {
705
+ condition: i18n,
706
+ plugins: async () => {
707
+ return [
708
+ viteVueI18nPlugin({
709
+ compositionOnly: true,
710
+ fullInstall: true,
711
+ runtimeOnly: true
712
+ })
713
+ ];
714
+ }
715
+ },
716
+ {
717
+ condition: print,
718
+ plugins: async () => {
719
+ return [await vitePrintPlugin({ infoMap: printInfoMap })];
720
+ }
721
+ },
722
+ {
723
+ condition: vxeTableLazyImport,
724
+ plugins: async () => {
725
+ return [await viteVxeTableImportsPlugin()];
726
+ }
727
+ },
728
+ {
729
+ condition: nitroMock,
730
+ plugins: async () => {
731
+ return [await viteNitroMockPlugin(nitroMockOptions)];
732
+ }
733
+ },
734
+ {
735
+ condition: injectAppLoading,
736
+ plugins: async () => [await viteInjectAppLoadingPlugin(!!isBuild, env)]
737
+ },
738
+ {
739
+ condition: license,
740
+ plugins: async () => [await viteLicensePlugin()]
741
+ },
742
+ {
743
+ condition: pwa,
744
+ plugins: () => VitePWA({
745
+ injectRegister: false,
746
+ workbox: {
747
+ globPatterns: []
748
+ },
749
+ ...pwaOptions,
750
+ manifest: {
751
+ display: "standalone",
752
+ start_url: "/",
753
+ theme_color: "#ffffff",
754
+ ...pwaOptions?.manifest
755
+ }
756
+ })
757
+ },
758
+ {
759
+ condition: isBuild && !!compress,
760
+ plugins: () => {
761
+ const compressPlugins = [];
762
+ if (compressTypes?.includes("brotli")) {
763
+ compressPlugins.push(
764
+ viteCompressPlugin({
765
+ algorithm: "brotliCompress",
766
+ ext: ".br",
767
+ threshold: 10 * 1024,
768
+ deleteOriginFile: false,
769
+ compressionOptions: {
770
+ params: {
771
+ [constants.BROTLI_PARAM_QUALITY]: 11,
772
+ [constants.BROTLI_PARAM_MODE]: constants.BROTLI_MODE_TEXT
773
+ }
774
+ }
775
+ })
776
+ );
777
+ }
778
+ if (compressTypes?.includes("gzip")) {
779
+ compressPlugins.push(
780
+ viteCompressPlugin({ deleteOriginFile: false, ext: ".gz" })
781
+ );
782
+ }
783
+ return compressPlugins;
784
+ }
785
+ },
786
+ {
787
+ condition: !!html,
788
+ plugins: () => [createHtmlPlugin({ minify: true })]
789
+ },
790
+ {
791
+ condition: isBuild && importmap,
792
+ plugins: () => {
793
+ return [viteImportMapPlugin(importmapOptions)];
794
+ }
795
+ },
796
+ {
797
+ condition: isBuild && extraAppConfig,
798
+ plugins: async () => [
799
+ await viteExtraAppConfigPlugin({
800
+ env: env || {},
801
+ isBuild: true,
802
+ root: process.cwd()
803
+ })
804
+ ]
805
+ },
806
+ {
807
+ condition: archiver,
808
+ plugins: async () => {
809
+ return [await viteArchiverPlugin(archiverPluginOptions)];
810
+ }
811
+ }
812
+ ]);
813
+ }
814
+ async function loadLibraryPlugins(options) {
815
+ const isBuild = options.isBuild;
816
+ const { dts, ...commonOptions } = options;
817
+ const commonPlugins = await loadCommonPlugins(commonOptions);
818
+ return await loadConditionPlugins([
819
+ ...commonPlugins,
820
+ {
821
+ condition: isBuild && !!dts,
822
+ plugins: () => [viteDtsPlugin({ logLevel: "error" })]
823
+ }
824
+ ]);
825
+ }
826
+
827
+ const getBoolean = (value) => value === "true";
828
+ const getString = (value, fallback) => value ?? fallback;
829
+ const getNumber = (value, fallback) => Number(value) || fallback;
830
+ function getConfFiles() {
831
+ const script = process.env.npm_lifecycle_script;
832
+ const reg = /--mode ([\d_a-z]+)/;
833
+ const result = reg.exec(script);
834
+ let mode = "production";
835
+ if (result) {
836
+ mode = result[1];
837
+ }
838
+ return [".env", ".env.local", `.env.${mode}`, `.env.${mode}.local`];
839
+ }
840
+ async function loadEnv(match = "VITE_GLOB_", confFiles = getConfFiles()) {
841
+ let envConfig = {};
842
+ for (const confFile of confFiles) {
843
+ try {
844
+ const confFilePath = join(process.cwd(), confFile);
845
+ if (existsSync(confFilePath)) {
846
+ const envPath = await fs$1.readFile(confFilePath, {
847
+ encoding: "utf8"
848
+ });
849
+ const env = dotenv.parse(envPath);
850
+ envConfig = { ...envConfig, ...env };
851
+ }
852
+ } catch (error) {
853
+ console.error(`Error while parsing ${confFile}`, error);
854
+ }
855
+ }
856
+ const reg = new RegExp(`^(${match})`);
857
+ Object.keys(envConfig).forEach((key) => {
858
+ if (!reg.test(key)) {
859
+ Reflect.deleteProperty(envConfig, key);
860
+ }
861
+ });
862
+ return envConfig;
863
+ }
864
+ async function loadAndConvertEnv(match = "VITE_", confFiles = getConfFiles()) {
865
+ const envConfig = await loadEnv(match, confFiles);
866
+ const {
867
+ VITE_APP_TITLE,
868
+ VITE_ARCHIVER,
869
+ VITE_BASE,
870
+ VITE_COMPRESS,
871
+ VITE_DEVTOOLS,
872
+ VITE_INJECT_APP_LOADING,
873
+ VITE_NITRO_MOCK,
874
+ VITE_PORT,
875
+ VITE_PWA,
876
+ VITE_VISUALIZER
877
+ } = envConfig;
878
+ const compressTypes = (VITE_COMPRESS ?? "").split(",").filter((item) => item === "brotli" || item === "gzip");
879
+ return {
880
+ appTitle: getString(VITE_APP_TITLE, "Vben Admin"),
881
+ archiver: getBoolean(VITE_ARCHIVER),
882
+ base: getString(VITE_BASE, "/"),
883
+ compress: compressTypes.length > 0,
884
+ compressTypes,
885
+ devtools: getBoolean(VITE_DEVTOOLS),
886
+ injectAppLoading: getBoolean(VITE_INJECT_APP_LOADING),
887
+ nitroMock: getBoolean(VITE_NITRO_MOCK),
888
+ port: getNumber(VITE_PORT, 5173),
889
+ pwa: getBoolean(VITE_PWA),
890
+ visualizer: getBoolean(VITE_VISUALIZER)
891
+ };
892
+ }
893
+
894
+ async function getCommonConfig() {
895
+ return {
896
+ build: {
897
+ chunkSizeWarningLimit: 2e3,
898
+ reportCompressedSize: false,
899
+ sourcemap: false
900
+ }
901
+ };
902
+ }
903
+
904
+ function defineApplicationConfig(userConfigPromise) {
905
+ return defineConfig$1(async (config) => {
906
+ const options = await userConfigPromise?.(config);
907
+ const { appTitle, base, port, ...envConfig } = await loadAndConvertEnv();
908
+ const { command, mode } = config;
909
+ const { application = {}, vite = {} } = options || {};
910
+ const root = process.cwd();
911
+ const isBuild = command === "build";
912
+ const env = loadEnv$1(mode, root);
913
+ const plugins = await loadApplicationPlugins({
914
+ archiver: true,
915
+ archiverPluginOptions: {},
916
+ compress: isBuild,
917
+ compressTypes: ["brotli", "gzip"],
918
+ devtools: true,
919
+ env,
920
+ extraAppConfig: true,
921
+ html: true,
922
+ i18n: true,
923
+ importmapOptions: defaultImportmapOptions,
924
+ injectAppLoading: true,
925
+ injectMetadata: true,
926
+ isBuild,
927
+ license: true,
928
+ mode,
929
+ nitroMock: !isBuild,
930
+ nitroMockOptions: {},
931
+ print: !isBuild,
932
+ printInfoMap: {
933
+ "Vben Admin Docs": "https://doc.vben.pro"
934
+ },
935
+ pwa: true,
936
+ pwaOptions: getDefaultPwaOptions(appTitle),
937
+ vxeTableLazyImport: true,
938
+ ...envConfig,
939
+ ...application
940
+ });
941
+ const { injectGlobalScss = true } = application;
942
+ const applicationConfig = {
943
+ base,
944
+ build: {
945
+ rollupOptions: {
946
+ output: {
947
+ assetFileNames: "[ext]/[name]-[hash].[ext]",
948
+ chunkFileNames: "js/[name]-[hash].js",
949
+ entryFileNames: "jse/index-[name]-[hash].js",
950
+ manualChunks(id) {
951
+ if (id.includes("@iconify/json/json/mdi.json")) {
952
+ return "mdi-icons";
953
+ }
954
+ if (id.includes("node_modules/vue/") || id.includes("node_modules/@vue/")) {
955
+ return "vendor-vue";
956
+ }
957
+ if (id.includes("node_modules/vue-router/")) {
958
+ return "vendor-vue-router";
959
+ }
960
+ if (id.includes("node_modules/pinia/")) {
961
+ return "vendor-pinia";
962
+ }
963
+ if (id.includes("node_modules/ant-design-vue/")) {
964
+ return "vendor-ant-design-vue";
965
+ }
966
+ if (id.includes("node_modules/vxe-table/") || id.includes("node_modules/vxe-pc-ui/")) {
967
+ return "vendor-vxe-table";
968
+ }
969
+ if (id.includes("node_modules/echarts/")) {
970
+ return "vendor-echarts";
971
+ }
972
+ if (id.includes("node_modules/")) {
973
+ if (id.includes("lodash")) {
974
+ return "vendor-lodash";
975
+ }
976
+ if (id.includes("dayjs")) {
977
+ return "vendor-dayjs";
978
+ }
979
+ if (id.includes("axios")) {
980
+ return "vendor-axios";
981
+ }
982
+ }
983
+ }
984
+ }
985
+ },
986
+ chunkSizeWarningLimit: 1500,
987
+ minify: "esbuild",
988
+ target: "es2015"
989
+ },
990
+ css: createCssOptions(injectGlobalScss),
991
+ esbuild: {
992
+ drop: isBuild ? [
993
+ "console",
994
+ "debugger"
995
+ ] : [],
996
+ legalComments: "none"
997
+ },
998
+ plugins,
999
+ server: {
1000
+ host: true,
1001
+ port,
1002
+ warmup: {
1003
+ // 预热文件
1004
+ clientFiles: [
1005
+ "./index.html",
1006
+ "./src/bootstrap.ts",
1007
+ "./src/{views,layouts,router,store,api,adapter}/*"
1008
+ ]
1009
+ }
1010
+ }
1011
+ };
1012
+ const mergedCommonConfig = mergeConfig(
1013
+ await getCommonConfig(),
1014
+ applicationConfig
1015
+ );
1016
+ return mergeConfig(mergedCommonConfig, vite);
1017
+ });
1018
+ }
1019
+ function createCssOptions(injectGlobalScss = true) {
1020
+ const root = findMonorepoRoot();
1021
+ return {
1022
+ preprocessorOptions: injectGlobalScss ? {
1023
+ scss: {
1024
+ additionalData: (content, filepath) => {
1025
+ const relativePath = relative(root, filepath);
1026
+ if (relativePath.startsWith(`apps${path.sep}`)) {
1027
+ return `@use "@vben/styles/global" as *;
1028
+ ${content}`;
1029
+ }
1030
+ return content;
1031
+ },
1032
+ api: "modern",
1033
+ importers: [new NodePackageImporter()]
1034
+ }
1035
+ } : {}
1036
+ };
1037
+ }
1038
+
1039
+ function defineLibraryConfig(userConfigPromise) {
1040
+ return defineConfig$1(async (config) => {
1041
+ const options = await userConfigPromise?.(config);
1042
+ const { command, mode } = config;
1043
+ const { library = {}, vite = {} } = options || {};
1044
+ const root = process.cwd();
1045
+ const isBuild = command === "build";
1046
+ const plugins = await loadLibraryPlugins({
1047
+ dts: false,
1048
+ injectMetadata: true,
1049
+ isBuild,
1050
+ mode,
1051
+ ...library
1052
+ });
1053
+ const { dependencies = {}, peerDependencies = {} } = await readPackageJSON(root);
1054
+ const externalPackages = [
1055
+ ...Object.keys(dependencies),
1056
+ ...Object.keys(peerDependencies)
1057
+ ];
1058
+ const packageConfig = {
1059
+ build: {
1060
+ lib: {
1061
+ entry: "src/index.ts",
1062
+ fileName: () => "index.mjs",
1063
+ formats: ["es"]
1064
+ },
1065
+ rollupOptions: {
1066
+ external: (id) => {
1067
+ return externalPackages.some(
1068
+ (pkg) => id === pkg || id.startsWith(`${pkg}/`)
1069
+ );
1070
+ }
1071
+ }
1072
+ },
1073
+ plugins
1074
+ };
1075
+ const commonConfig = await getCommonConfig();
1076
+ const mergedConmonConfig = mergeConfig(commonConfig, packageConfig);
1077
+ return mergeConfig(mergedConmonConfig, vite);
1078
+ });
1079
+ }
1080
+
1081
+ function defineConfig(userConfigPromise, type = "auto") {
1082
+ let projectType = type;
1083
+ if (projectType === "auto") {
1084
+ const htmlPath = join(process.cwd(), "index.html");
1085
+ projectType = existsSync(htmlPath) ? "application" : "library";
1086
+ }
1087
+ switch (projectType) {
1088
+ case "application": {
1089
+ return defineApplicationConfig(userConfigPromise);
1090
+ }
1091
+ case "library": {
1092
+ return defineLibraryConfig(userConfigPromise);
1093
+ }
1094
+ default: {
1095
+ throw new Error(`Unsupported project type: ${projectType}`);
1096
+ }
1097
+ }
1098
+ }
1099
+
1100
+ export { defaultImportmapOptions, defineApplicationConfig, defineConfig, defineLibraryConfig, getDefaultPwaOptions, loadAndConvertEnv, loadApplicationPlugins, loadLibraryPlugins, viteArchiverPlugin, viteVxeTableImportsPlugin };
package/package.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "name": "@dcf-micro/vite-config",
3
+ "version": "5.5.9",
4
+ "homepage": "https://github.com/vbenjs/vue-vben-admin",
5
+ "bugs": "https://github.com/vbenjs/vue-vben-admin/issues",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/vbenjs/vue-vben-admin.git",
9
+ "directory": "internal/vite-config"
10
+ },
11
+ "license": "MIT",
12
+ "type": "module",
13
+ "scripts": {
14
+ "build": "pnpm unbuild",
15
+ "stub": "pnpm unbuild --stub"
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "main": "./dist/index.mjs",
21
+ "module": "./dist/index.mjs",
22
+ "types": "./dist/index.d.ts",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./src/index.ts",
26
+ "default": "./dist/index.mjs"
27
+ }
28
+ },
29
+ "publishConfig": {
30
+ "exports": {
31
+ ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "default": "./dist/index.mjs"
34
+ }
35
+ }
36
+ },
37
+ "dependencies": {
38
+ "@pnpm/workspace.read-manifest": "catalog:",
39
+ "@dcf-micro/utils-node": "workspace:*",
40
+ "@vitejs/plugin-vue": "catalog:",
41
+ "@vitejs/plugin-vue-jsx": "catalog:",
42
+ "@intlify/unplugin-vue-i18n": "catalog:",
43
+ "@jspm/generator": "catalog:",
44
+ "archiver": "catalog:",
45
+ "cheerio": "catalog:",
46
+ "dotenv": "catalog:",
47
+ "get-port": "catalog:",
48
+ "html-minifier-terser": "catalog:",
49
+ "nitropack": "catalog:",
50
+ "resolve.exports": "catalog:",
51
+ "rollup-plugin-visualizer": "catalog:",
52
+ "sass": "catalog:",
53
+ "vite": "catalog:",
54
+ "vite-plugin-compression": "catalog:",
55
+ "vite-plugin-dts": "catalog:",
56
+ "vite-plugin-html": "catalog:",
57
+ "vite-plugin-lazy-import": "catalog:",
58
+ "vite-plugin-pwa": "catalog:",
59
+ "vite-plugin-vue-devtools": "catalog:"
60
+ },
61
+ "devDependencies": {
62
+ "@types/archiver": "catalog:",
63
+ "@types/html-minifier-terser": "catalog:",
64
+ "dayjs": "catalog:",
65
+ "rollup": "catalog:"
66
+ }
67
+ }