@octohash/vite-config 0.2.2 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js DELETED
@@ -1,497 +0,0 @@
1
- import { __dirname, init_esm_shims } from "./esm-shims-CLMD_LGJ.js";
2
- import { isPackageExists } from "local-pkg";
3
- import { defineConfig as defineConfig$1, mergeConfig } from "vite";
4
- import { existsSync } from "node:fs";
5
- import path, { isAbsolute, join, resolve } from "node:path";
6
- import process from "node:process";
7
- import deepmerge from "deepmerge";
8
- import { findUp } from "find-up";
9
- import { readPackageJSON } from "pkg-types";
10
- import { fileURLToPath } from "node:url";
11
- import fsp from "node:fs/promises";
12
- import { visualizer } from "rollup-plugin-visualizer";
13
- import { EOL } from "node:os";
14
- import dayjs from "dayjs";
15
- import Vue from "@vitejs/plugin-vue";
16
- import VueJsx from "@vitejs/plugin-vue-jsx";
17
- import Dts from "vite-plugin-dts";
18
-
19
- //#region src/utils.ts
20
- function getProjectType() {
21
- const htmlPath = join(process.cwd(), "index.html");
22
- return existsSync(htmlPath) ? "app" : "lib";
23
- }
24
- async function loadMergedPackageJson() {
25
- const root = process.cwd();
26
- const rootPkgJsonPath = await findUp("pnpm-lock.yaml", {
27
- cwd: root,
28
- type: "file"
29
- });
30
- const rootPkgJson = rootPkgJsonPath ? await readPackageJSON(rootPkgJsonPath) : {};
31
- const pkgJson = await readPackageJSON(root);
32
- return deepmerge(rootPkgJson, pkgJson);
33
- }
34
- function extractAuthorInfo(pkgJson) {
35
- const { author } = pkgJson;
36
- const isObject = typeof author === "object";
37
- const name = isObject ? author.name : author;
38
- const email = isObject ? author.email : void 0;
39
- const url = isObject ? author.url : void 0;
40
- return {
41
- name,
42
- email,
43
- url
44
- };
45
- }
46
- async function loadConditionPlugins(conditionPlugins) {
47
- const plugins = [];
48
- for (const conditionPlugin of conditionPlugins) if (conditionPlugin.condition) {
49
- const realPlugins = await conditionPlugin.plugins();
50
- plugins.push(...realPlugins);
51
- }
52
- return plugins.flat();
53
- }
54
- function resolveSubOptions(options, key) {
55
- return typeof options[key] === "boolean" ? {} : options[key] || {};
56
- }
57
-
58
- //#endregion
59
- //#region src/plugins/app-loading/index.ts
60
- init_esm_shims();
61
- const INJECT_SCRIPT = `
62
- <script data-app-loading="inject-js">
63
- ;(function () {
64
- const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
65
- const setting = localStorage.getItem('vueuse-color-scheme') || 'auto'
66
- if (setting === 'dark' || (prefersDark && setting !== 'light'))
67
- document.documentElement.classList.toggle('dark', true)
68
- })()
69
- </script>
70
- `;
71
- async function AppLoadingPlugin(options) {
72
- const { rootContainer = "app", title = "", filePath = path.join(__dirname, "./default-loading.html") } = options || {};
73
- const loadingHtml = await getLoadingRawByHtmlTemplate(filePath);
74
- return {
75
- name: "vite-plugin-app-loading",
76
- enforce: "pre",
77
- transformIndexHtml: {
78
- order: "pre",
79
- handler: (html) => {
80
- const rootContainerPattern = new RegExp(`<div id="${rootContainer}"\\s*></div>`, "i");
81
- if (!rootContainerPattern.test(html)) return html;
82
- const processedLoadingHtml = loadingHtml.replace("[app-loading-title]", title);
83
- const injectedContent = `${INJECT_SCRIPT}${processedLoadingHtml}`;
84
- return html.replace(rootContainerPattern, `<div id="${rootContainer}">${injectedContent}</div>`);
85
- }
86
- }
87
- };
88
- }
89
- async function getLoadingRawByHtmlTemplate(filePath) {
90
- return await fsp.readFile(filePath, "utf8");
91
- }
92
-
93
- //#endregion
94
- //#region src/ensure.ts
95
- const scopeUrl = fileURLToPath(new URL(".", import.meta.url));
96
- const isCwdInScope = isPackageExists("@octohash/vite-config");
97
- function isPackageInScope(name) {
98
- return isPackageExists(name, { paths: [scopeUrl] });
99
- }
100
- async function ensurePackages(packages) {
101
- if (process.env.CI || process.stdout.isTTY === false || isCwdInScope === false) return;
102
- const nonExistingPackages = packages.filter((i) => i && !isPackageInScope(i));
103
- if (nonExistingPackages.length === 0) return;
104
- const p = await import("@clack/prompts");
105
- const result = await p.confirm({ message: `${nonExistingPackages.length === 1 ? "Package is" : "Packages are"} required for this config: ${nonExistingPackages.join(", ")}. Do you want to install them?` });
106
- if (result) await import("@antfu/install-pkg").then((i) => i.installPackage(nonExistingPackages, { dev: true }));
107
- }
108
-
109
- //#endregion
110
- //#region src/plugins/license.ts
111
- async function LicensePlugin(options) {
112
- const licenseText = await generateLicenseText(options || {});
113
- return {
114
- name: "vite-plugin-license",
115
- enforce: "post",
116
- apply: "build",
117
- generateBundle: {
118
- order: "post",
119
- handler: (_options, bundle) => {
120
- for (const [, fileContent] of Object.entries(bundle)) if (fileContent.type === "chunk" && fileContent.isEntry) {
121
- const chunkContent = fileContent;
122
- const content = chunkContent.code;
123
- const updatedContent = `${licenseText}${EOL}${content}`;
124
- fileContent.code = updatedContent;
125
- }
126
- }
127
- }
128
- };
129
- }
130
- async function generateLicenseText(options) {
131
- const pkgJson = await loadMergedPackageJson();
132
- const { name: authorName, email: authorEmail, url: authorUrl } = extractAuthorInfo(pkgJson);
133
- const { name = pkgJson.name, author = authorName, version = pkgJson.version, description = pkgJson.description, homepage = pkgJson.homepage ?? authorUrl, license, contact = authorEmail, copyright = {
134
- holder: authorName,
135
- year: new Date().getFullYear()
136
- } } = options ?? {};
137
- const date = dayjs().format("YYYY-MM-DD");
138
- const lines = [];
139
- lines.push("/*!");
140
- if (name) lines.push(` * ${name}`);
141
- if (version) lines.push(` * Version: ${version}`);
142
- if (author) lines.push(` * Author: ${author}`);
143
- if (license) lines.push(` * License: ${license}`);
144
- if (description) lines.push(` * Description: ${description}`);
145
- if (homepage) lines.push(` * Homepage: ${homepage}`);
146
- if (contact) lines.push(` * Contact: ${contact}`);
147
- if (copyright?.holder) lines.push(` * Copyright (C) ${copyright.year} ${copyright.holder}`);
148
- if (date) lines.push(` * Date: ${date}`);
149
- lines.push(" */");
150
- return lines.join("\n");
151
- }
152
-
153
- //#endregion
154
- //#region src/plugins/common.ts
155
- async function loadCommonPlugins(options) {
156
- const { isBuild, visualizer: visualizer$1 = false, license = true, federation } = options;
157
- ensurePackages([federation ? "@originjs/vite-plugin-federation" : void 0]);
158
- return await loadConditionPlugins([
159
- {
160
- condition: isBuild && !!visualizer$1,
161
- plugins: () => [visualizer(typeof visualizer$1 === "boolean" ? {
162
- filename: "./node_modules/.cache/visualizer/stats.html",
163
- gzipSize: true,
164
- open: true
165
- } : visualizer$1)]
166
- },
167
- {
168
- condition: isBuild && !!license,
169
- plugins: async () => [await LicensePlugin(typeof license === "boolean" ? void 0 : license)]
170
- },
171
- {
172
- condition: !!federation,
173
- plugins: async () => {
174
- const module = await import("@originjs/vite-plugin-federation");
175
- return [module.default(federation)];
176
- }
177
- }
178
- ]);
179
- }
180
-
181
- //#endregion
182
- //#region src/plugins/import-map.ts
183
- const shimsSubpath = `dist/es-module-shims.js`;
184
- const providerShimsMap = {
185
- "jspm.io": `https://ga.jspm.io/npm:es-module-shims@{version}/${shimsSubpath}`,
186
- "jsdelivr": `https://cdn.jsdelivr.net/npm/es-module-shims@{version}/${shimsSubpath}`,
187
- "unpkg": `https://unpkg.com/es-module-shims@{version}/${shimsSubpath}`,
188
- "esm.sh": `https://esm.sh/es-module-shims@{version}/${shimsSubpath}`
189
- };
190
- async function ImportMapPlugin(options = {}) {
191
- await ensurePackages(["vite-plugin-jspm"]);
192
- const module = await import("vite-plugin-jspm");
193
- const { defaultProvider = "jspm.io", include = [], exclude = [] } = options;
194
- const [scan, mapping, post] = await module.default({
195
- ...options,
196
- pollyfillProvider: (version) => providerShimsMap[defaultProvider]?.replace("{version}", version)
197
- });
198
- const _resolveId = scan.resolveId;
199
- scan.resolveId = function(id, importer, ctx) {
200
- if (include.length && !include.includes(id) || exclude.length && exclude.includes(id)) return null;
201
- return typeof _resolveId === "function" ? _resolveId.call(this, id, importer, ctx) : null;
202
- };
203
- const _load = mapping.load;
204
- mapping.load = function(id) {
205
- if (include.length && !include.includes(id)) return null;
206
- return typeof _load === "function" ? _load.call(this, id) : null;
207
- };
208
- return [
209
- scan,
210
- mapping,
211
- post
212
- ];
213
- }
214
-
215
- //#endregion
216
- //#region src/plugins/metadata.ts
217
- async function MetadataPlugin(options) {
218
- const { extendMetadata = {} } = options ?? {};
219
- const pkgJson = await loadMergedPackageJson();
220
- const { name, description, homepage, license, version } = pkgJson;
221
- const { name: authorName, email: authorEmail, url: authorUrl } = extractAuthorInfo(pkgJson);
222
- const buildTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
223
- return {
224
- name: "vite-plugin-metadata",
225
- enforce: "post",
226
- config: () => {
227
- return { define: { __VITE_APP_METADATA__: JSON.stringify({
228
- authorName,
229
- authorEmail,
230
- authorUrl,
231
- buildTime,
232
- name,
233
- description,
234
- homepage,
235
- license,
236
- version,
237
- ...extendMetadata
238
- }) } };
239
- }
240
- };
241
- }
242
-
243
- //#endregion
244
- //#region src/plugins/vue.ts
245
- async function loadVuePlugins(projectType, options) {
246
- const { isBuild } = options;
247
- const isApp = projectType === "app";
248
- const { devtools = false, i18n = false, imports = isApp, components = isApp, pages = isApp } = resolveSubOptions(options, "vue");
249
- await ensurePackages([devtools ? "vite-plugin-vue-devtools" : void 0, i18n ? "@intlify/unplugin-vue-i18n" : void 0]);
250
- return loadConditionPlugins([
251
- {
252
- condition: true,
253
- plugins: () => [Vue(), VueJsx()]
254
- },
255
- {
256
- condition: !isBuild && !!devtools,
257
- plugins: async () => {
258
- const module = await import("vite-plugin-vue-devtools");
259
- return [module.default(typeof devtools === "boolean" ? void 0 : devtools)];
260
- }
261
- },
262
- {
263
- condition: !!i18n,
264
- plugins: async () => {
265
- const module = await import("./vite-D44mTpAn.js");
266
- return [module.default(typeof i18n === "boolean" ? {
267
- compositionOnly: true,
268
- fullInstall: true,
269
- runtimeOnly: true
270
- } : i18n)];
271
- }
272
- },
273
- {
274
- condition: isApp && !!imports,
275
- plugins: async () => {
276
- const module = await import("unplugin-auto-import/vite");
277
- return [module.default(typeof imports === "boolean" ? {
278
- dts: "src/typings/auto-imports.d.ts",
279
- imports: await resolveAutoImports(),
280
- resolvers: await resolveUIComponentResolvers(),
281
- dirs: ["src/composables", "src/utils"],
282
- vueTemplate: true
283
- } : imports)];
284
- }
285
- },
286
- {
287
- condition: isApp && !!components,
288
- plugins: async () => {
289
- const module = await import("unplugin-vue-components/vite");
290
- return [module.default(typeof components === "boolean" ? {
291
- dts: "src/typings/components.d.ts",
292
- directoryAsNamespace: true
293
- } : components)];
294
- }
295
- },
296
- {
297
- condition: isApp && !!pages,
298
- plugins: async () => {
299
- const module = await import("unplugin-vue-router/vite");
300
- return [module.default(typeof pages === "boolean" ? { dts: "src/typings/typed-router.d.ts" } : pages)];
301
- }
302
- }
303
- ]);
304
- }
305
- async function resolveAutoImports() {
306
- const imports = ["vue"];
307
- if (isPackageExists("vue-router")) imports.push("vue-router");
308
- if (isPackageExists("pinia")) imports.push("pinia");
309
- if (isPackageExists("@vueuse/core")) imports.push("@vueuse/core");
310
- if (isPackageExists("vue-i18n")) imports.push("vue-i18n");
311
- return imports;
312
- }
313
- async function resolveUIComponentResolvers() {
314
- const resolvers = [];
315
- if (isPackageExists("ant-design-vue")) {
316
- const { AntDesignVueResolver } = await import("unplugin-vue-components/resolvers");
317
- resolvers.push(AntDesignVueResolver({
318
- importStyle: "css-in-js",
319
- prefix: ""
320
- }));
321
- }
322
- if (isPackageExists("element-plus")) {
323
- const { ElementPlusResolver } = await import("unplugin-vue-components/resolvers");
324
- resolvers.push(...ElementPlusResolver());
325
- }
326
- if (isPackageExists("naive-ui")) {
327
- const { NaiveUiResolver } = await import("unplugin-vue-components/resolvers");
328
- resolvers.push(NaiveUiResolver());
329
- }
330
- if (isPackageExists("vant")) {
331
- const { VantResolver } = await import("unplugin-vue-components/resolvers");
332
- resolvers.push(VantResolver());
333
- }
334
- return resolvers;
335
- }
336
-
337
- //#endregion
338
- //#region src/plugins/app.ts
339
- async function loadAppPlugins(options) {
340
- const { isBuild, dynamicBase, appLoading = true, metadata = true, importMap = false, vue } = options;
341
- const plugins = await loadCommonPlugins(options);
342
- plugins.push(await loadConditionPlugins([
343
- {
344
- condition: !!dynamicBase,
345
- plugins: async () => {
346
- const module = await import("vite-plugin-dynamic-base");
347
- return [module.dynamicBase({
348
- publicPath: dynamicBase,
349
- transformIndexHtml: true
350
- })];
351
- }
352
- },
353
- {
354
- condition: !!appLoading,
355
- plugins: async () => [await AppLoadingPlugin(typeof appLoading === "boolean" ? void 0 : appLoading)]
356
- },
357
- {
358
- condition: !!metadata,
359
- plugins: async () => {
360
- return [await MetadataPlugin(typeof metadata === "boolean" ? void 0 : metadata)];
361
- }
362
- },
363
- {
364
- condition: isBuild && !!importMap,
365
- plugins: () => {
366
- return [ImportMapPlugin(typeof importMap === "boolean" ? void 0 : importMap)];
367
- }
368
- }
369
- ]));
370
- if (vue) plugins.push(await loadVuePlugins("app", options));
371
- return plugins;
372
- }
373
-
374
- //#endregion
375
- //#region src/config/common.ts
376
- async function getCommonConfig(options) {
377
- const { alias = {} } = options;
378
- const resolvedAlias = Object.entries(alias).reduce((acc, [key, value]) => {
379
- acc[key] = isAbsolute(value) ? value : resolve(process.cwd(), value);
380
- return acc;
381
- }, {});
382
- return {
383
- resolve: { alias: {
384
- "@": resolve(process.cwd(), "./src"),
385
- ...resolvedAlias
386
- } },
387
- build: {
388
- chunkSizeWarningLimit: 2e3,
389
- reportCompressedSize: false,
390
- sourcemap: false
391
- }
392
- };
393
- }
394
-
395
- //#endregion
396
- //#region src/config/app.ts
397
- function defineAppConfig(options) {
398
- return defineConfig$1(async (config) => {
399
- const { dynamicBase, vite = {} } = options;
400
- const { command } = config;
401
- const isBuild = command === "build";
402
- const plugins = await loadAppPlugins({
403
- ...options,
404
- isBuild
405
- });
406
- const appConfig = {
407
- base: dynamicBase ? "/__dynamic_base__/" : "/",
408
- plugins,
409
- build: {
410
- target: "es2015",
411
- rollupOptions: { output: {
412
- assetFileNames: "[ext]/[name]-[hash].[ext]",
413
- chunkFileNames: "js/[name]-[hash].js",
414
- entryFileNames: "jse/index-[name]-[hash].js"
415
- } }
416
- },
417
- esbuild: {
418
- drop: isBuild ? ["debugger"] : [],
419
- legalComments: "none"
420
- },
421
- server: { host: true }
422
- };
423
- const mergedCommonConfig = mergeConfig(await getCommonConfig(options), appConfig);
424
- return mergeConfig(mergedCommonConfig, vite);
425
- });
426
- }
427
-
428
- //#endregion
429
- //#region src/plugins/lib.ts
430
- async function loadLibPlugins(options) {
431
- const { isBuild, dts = true, vue } = options;
432
- const plugins = await loadCommonPlugins(options);
433
- plugins.push(await loadConditionPlugins([{
434
- condition: isBuild && !!dts,
435
- plugins: () => [Dts(typeof dts === "boolean" ? { logLevel: "error" } : dts)]
436
- }]));
437
- if (vue) plugins.push(await loadVuePlugins("lib", options));
438
- return plugins;
439
- }
440
-
441
- //#endregion
442
- //#region src/config/lib.ts
443
- function defineLibConfig(options) {
444
- return defineConfig$1(async (config) => {
445
- const root = process.cwd();
446
- const { vite = {} } = options;
447
- const { command } = config;
448
- const isBuild = command === "build";
449
- const plugins = await loadLibPlugins({
450
- ...options,
451
- isBuild
452
- });
453
- const { dependencies = {}, peerDependencies = {} } = await readPackageJSON(root);
454
- const externalPackages = [...Object.keys(dependencies), ...Object.keys(peerDependencies)];
455
- const libConfig = {
456
- plugins,
457
- build: {
458
- lib: {
459
- entry: "src/index.ts",
460
- fileName: () => "index.mjs",
461
- formats: ["es"]
462
- },
463
- rollupOptions: { external: (id) => {
464
- return externalPackages.some((pkg) => id === pkg || id.startsWith(`${pkg}/`));
465
- } }
466
- }
467
- };
468
- const mergedCommonConfig = mergeConfig(await getCommonConfig(options), libConfig);
469
- return mergeConfig(mergedCommonConfig, vite);
470
- });
471
- }
472
-
473
- //#endregion
474
- //#region src/constants.ts
475
- const VUE_PACKAGES = [
476
- "vue",
477
- "nuxt",
478
- "vitepress"
479
- ];
480
-
481
- //#endregion
482
- //#region src/index.ts
483
- function defineConfig(options) {
484
- const resolved = {
485
- type: getProjectType(),
486
- vue: VUE_PACKAGES.some((pkg) => isPackageExists(pkg)),
487
- ...options
488
- };
489
- switch (resolved.type) {
490
- case "app": return defineAppConfig(resolved);
491
- case "lib": return defineLibConfig(resolved);
492
- default: throw new Error(`Unsupported project type: ${resolved.type}`);
493
- }
494
- }
495
-
496
- //#endregion
497
- export { defineConfig };