vite-plugin-build-version-file 0.1.11 → 0.1.13

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/README.md CHANGED
@@ -7,6 +7,7 @@
7
7
  - 开发态通过 dev server 提供 `version.json`
8
8
  - 构建后在输出目录生成 `version.json`
9
9
  - 普通 Vite HTML 自动注入 `window["__VERSION__"]`
10
+ - 可选通过 `define` 将同一份 payload 编译进 JS 产物
10
11
  - VitePress 可通过顶层 `transformHtml` 注入同一份版本信息
11
12
  - 支持自定义版本号、输出文件名、全局变量名、时区和额外字段
12
13
 
@@ -127,6 +128,7 @@ type BuildVersionContext = {
127
128
  type BuildVersionPluginOptions = {
128
129
  filename?: string
129
130
  globalName?: string
131
+ defineName?: string | false
130
132
  injectToHtml?: boolean
131
133
  timeZone?: string
132
134
  version?: string | number | ((ctx: BuildVersionContext) => string | number)
@@ -180,6 +182,36 @@ dist/meta/version.json
180
182
 
181
183
  这里注入的是完整 payload 对象,不是单独版本字符串。
182
184
 
185
+ ### `defineName`
186
+
187
+ - 类型:`string | false`
188
+ - 默认值:`"__VERSION__"`
189
+ - 作用:控制是否通过 Vite `define` 将完整 payload 编译进 JS 产物
190
+
191
+ 示例:
192
+
193
+ ```ts
194
+ buildVersionPlugin({
195
+ defineName: '__APP_VERSION__'
196
+ })
197
+ ```
198
+
199
+ 业务代码可直接读取:
200
+
201
+ ```ts
202
+ console.log(__APP_VERSION__)
203
+ ```
204
+
205
+ 打包后会在编译阶段被替换成字面量对象,因此适合给 Vue、TS、JS 模块直接消费。
206
+
207
+ 默认情况下会注入 `__VERSION__`。如果你不需要编译期常量,可显式传 `defineName: false` 关闭。
208
+
209
+ 如果同时开启 `defineName` 和 `globalName`,两者会共用同一份 payload:
210
+
211
+ - `defineName` 写入编译后的 JS
212
+ - `globalName` 注入运行时 HTML
213
+ - `version.json` 仍照常输出
214
+
183
215
  ### `injectToHtml`
184
216
 
185
217
  - 类型:`boolean`
@@ -350,6 +382,30 @@ checkVersion()
350
382
  - 弹窗、通知、静默刷新等策略放在业务项目里
351
383
  - 请求失败后继续下一轮检查,避免一次失败中断流程
352
384
 
385
+ ## 刷新指定项目缓存
386
+
387
+ ```ts
388
+ import { clearUrlCache } from 'vite-plugin-build-version-file/client'
389
+
390
+ await clearUrlCache('/vue-app/')
391
+ ```
392
+
393
+ `url` 可省略;省略时默认使用当前 Vue 项目页面 URL:
394
+
395
+ ```ts
396
+ await clearUrlCache()
397
+ ```
398
+
399
+ Vue hash 路由会原样保留,缓存时间戳写在 `#` 前,确保服务器能够收到:
400
+
401
+ ```text
402
+ https://cus.smarex.com.cn/pc/?_=随机值#/login?redirect=/dashboard/analysis
403
+ ```
404
+
405
+ 该方法仅支持同源 URL。它会绕过缓存请求 URL、强制刷新原 URL、通过隐藏 iframe 再次加载页面,最后携带随机时间戳跳转到该 URL。创建 iframe 前会销毁同一页面中已有的缓存刷新 iframe。单次请求或 iframe 加载失败不会阻断最终跳转。
406
+
407
+ 受浏览器限制,前端代码无法直接删除指定 URL 下的全部 HTTP 缓存;该方法只能尽可能刷新对应 Vue 项目的缓存。
408
+
353
409
  ## 开发态行为
354
410
 
355
411
  开发态下,插件不会向业务项目目录写入文件。
@@ -792,6 +848,30 @@ Recommendations:
792
848
  - Keep prompts, notifications, silent reloads, and retry rules in application code.
793
849
  - Continue polling after failed requests.
794
850
 
851
+ ## Refreshing a Project Cache
852
+
853
+ ```ts
854
+ import { clearUrlCache } from 'vite-plugin-build-version-file/client'
855
+
856
+ await clearUrlCache('/vue-app/')
857
+ ```
858
+
859
+ The `url` argument is optional. When omitted, the current Vue project page URL is used:
860
+
861
+ ```ts
862
+ await clearUrlCache()
863
+ ```
864
+
865
+ Vue hash routes are preserved. The cache-busting timestamp is added before `#` so the server receives it:
866
+
867
+ ```text
868
+ https://cus.smarex.com.cn/pc/?_=random-value#/login?redirect=/dashboard/analysis
869
+ ```
870
+
871
+ This method only supports same-origin URLs. It bypasses the cached URL, forces a refresh of the original URL, loads the page again in a hidden iframe, and finally navigates to the URL with a random timestamp. Any existing cache-refresh iframe created by this method is removed before a new one is created. A failed request or iframe load does not prevent the final navigation.
872
+
873
+ Browser code cannot directly delete every HTTP cache entry under a specific URL. This method refreshes the corresponding Vue application cache on a best-effort basis.
874
+
795
875
  ## Development Behavior
796
876
 
797
877
  In development, the plugin does not write files into your project directory.
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/client.ts
21
+ var client_exports = {};
22
+ __export(client_exports, {
23
+ clearUrlCache: () => clearUrlCache
24
+ });
25
+ module.exports = __toCommonJS(client_exports);
26
+ var CACHE_BUST_PARAM = "_";
27
+ var IFRAME_ID = "vite-plugin-build-version-file-cache-iframe";
28
+ var IFRAME_TIMEOUT = 5e3;
29
+ function createCacheBustedUrl(url) {
30
+ const targetUrl = new URL(url, window.location.href);
31
+ const hash = targetUrl.hash;
32
+ targetUrl.hash = "";
33
+ targetUrl.searchParams.set(
34
+ CACHE_BUST_PARAM,
35
+ `${Date.now()}-${Math.random().toString(36).slice(2)}`
36
+ );
37
+ targetUrl.hash = hash;
38
+ return targetUrl.href;
39
+ }
40
+ function loadIframe(url) {
41
+ return new Promise((resolve) => {
42
+ document.getElementById(IFRAME_ID)?.remove();
43
+ const iframe = document.createElement("iframe");
44
+ let completed = false;
45
+ const complete = () => {
46
+ if (completed) {
47
+ return;
48
+ }
49
+ completed = true;
50
+ window.clearTimeout(timeout);
51
+ resolve();
52
+ };
53
+ const timeout = window.setTimeout(complete, IFRAME_TIMEOUT);
54
+ iframe.hidden = true;
55
+ iframe.id = IFRAME_ID;
56
+ iframe.addEventListener("load", complete, { once: true });
57
+ iframe.addEventListener("error", complete, { once: true });
58
+ iframe.src = url;
59
+ document.documentElement.appendChild(iframe);
60
+ });
61
+ }
62
+ async function clearUrlCache(url = window.location.href) {
63
+ const targetUrl = new URL(url, window.location.href).href;
64
+ await Promise.allSettled([
65
+ fetch(createCacheBustedUrl(targetUrl), { cache: "no-store" }).then(
66
+ (response) => response.arrayBuffer()
67
+ ),
68
+ fetch(targetUrl, { cache: "reload" }).then(
69
+ (response) => response.arrayBuffer()
70
+ )
71
+ ]);
72
+ try {
73
+ await loadIframe(createCacheBustedUrl(targetUrl));
74
+ } finally {
75
+ window.location.replace(createCacheBustedUrl(targetUrl));
76
+ }
77
+ }
78
+ // Annotate the CommonJS export names for ESM import in node:
79
+ 0 && (module.exports = {
80
+ clearUrlCache
81
+ });
@@ -0,0 +1,3 @@
1
+ declare function clearUrlCache(url?: string): Promise<void>;
2
+
3
+ export { clearUrlCache };
@@ -0,0 +1,3 @@
1
+ declare function clearUrlCache(url?: string): Promise<void>;
2
+
3
+ export { clearUrlCache };
@@ -0,0 +1,56 @@
1
+ // src/client.ts
2
+ var CACHE_BUST_PARAM = "_";
3
+ var IFRAME_ID = "vite-plugin-build-version-file-cache-iframe";
4
+ var IFRAME_TIMEOUT = 5e3;
5
+ function createCacheBustedUrl(url) {
6
+ const targetUrl = new URL(url, window.location.href);
7
+ const hash = targetUrl.hash;
8
+ targetUrl.hash = "";
9
+ targetUrl.searchParams.set(
10
+ CACHE_BUST_PARAM,
11
+ `${Date.now()}-${Math.random().toString(36).slice(2)}`
12
+ );
13
+ targetUrl.hash = hash;
14
+ return targetUrl.href;
15
+ }
16
+ function loadIframe(url) {
17
+ return new Promise((resolve) => {
18
+ document.getElementById(IFRAME_ID)?.remove();
19
+ const iframe = document.createElement("iframe");
20
+ let completed = false;
21
+ const complete = () => {
22
+ if (completed) {
23
+ return;
24
+ }
25
+ completed = true;
26
+ window.clearTimeout(timeout);
27
+ resolve();
28
+ };
29
+ const timeout = window.setTimeout(complete, IFRAME_TIMEOUT);
30
+ iframe.hidden = true;
31
+ iframe.id = IFRAME_ID;
32
+ iframe.addEventListener("load", complete, { once: true });
33
+ iframe.addEventListener("error", complete, { once: true });
34
+ iframe.src = url;
35
+ document.documentElement.appendChild(iframe);
36
+ });
37
+ }
38
+ async function clearUrlCache(url = window.location.href) {
39
+ const targetUrl = new URL(url, window.location.href).href;
40
+ await Promise.allSettled([
41
+ fetch(createCacheBustedUrl(targetUrl), { cache: "no-store" }).then(
42
+ (response) => response.arrayBuffer()
43
+ ),
44
+ fetch(targetUrl, { cache: "reload" }).then(
45
+ (response) => response.arrayBuffer()
46
+ )
47
+ ]);
48
+ try {
49
+ await loadIframe(createCacheBustedUrl(targetUrl));
50
+ } finally {
51
+ window.location.replace(createCacheBustedUrl(targetUrl));
52
+ }
53
+ }
54
+ export {
55
+ clearUrlCache
56
+ };
package/dist/index.cjs CHANGED
@@ -29,6 +29,7 @@ var import_node_path = require("path");
29
29
  var PLUGIN_NAME = "vite-plugin-build-version-file";
30
30
  var DEFAULT_FILENAME = "version.json";
31
31
  var DEFAULT_GLOBAL_NAME = "__VERSION__";
32
+ var DEFAULT_DEFINE_NAME = "__VERSION__";
32
33
  var DEFAULT_TIME_ZONE = "Asia/Shanghai";
33
34
  function createDefaultVersion(command, timeZone) {
34
35
  if (command === "serve") {
@@ -70,6 +71,15 @@ function normalizeGlobalName(globalName) {
70
71
  }
71
72
  return globalName;
72
73
  }
74
+ function normalizeDefineName(defineName) {
75
+ if (defineName === false || defineName === void 0) {
76
+ return defineName ?? false;
77
+ }
78
+ if (!defineName.trim()) {
79
+ throw new Error(`[${PLUGIN_NAME}] "defineName" cannot be empty.`);
80
+ }
81
+ return defineName;
82
+ }
73
83
  function normalizeTimeZone(timeZone) {
74
84
  const normalized = timeZone.trim();
75
85
  if (!normalized) {
@@ -154,6 +164,9 @@ function toRequestPath(base, fileName) {
154
164
  const baseWithoutTrailingSlash = withLeadingSlash.endsWith("/") ? withLeadingSlash.slice(0, -1) : withLeadingSlash;
155
165
  return `${baseWithoutTrailingSlash}/${fileName}`.replace(/\/{2,}/g, "/");
156
166
  }
167
+ function resolveProjectRoot(root) {
168
+ return root ? (0, import_node_path.resolve)(process.cwd(), root) : process.cwd();
169
+ }
157
170
  function resolveVersion(options, context, timeZone) {
158
171
  if (typeof options.version === "function") {
159
172
  return options.version(context);
@@ -180,6 +193,9 @@ function buildVersionPlugin(options = {}) {
180
193
  const globalName = normalizeGlobalName(
181
194
  options.globalName ?? DEFAULT_GLOBAL_NAME
182
195
  );
196
+ const defineName = normalizeDefineName(
197
+ options.defineName ?? DEFAULT_DEFINE_NAME
198
+ );
183
199
  const injectToHtml = options.injectToHtml ?? true;
184
200
  const timeZone = normalizeTimeZone(options.timeZone ?? DEFAULT_TIME_ZONE);
185
201
  const data = normalizeData(options.data);
@@ -193,6 +209,24 @@ function buildVersionPlugin(options = {}) {
193
209
  };
194
210
  const plugin = {
195
211
  name: PLUGIN_NAME,
212
+ config(userConfig, env) {
213
+ if (!payload) {
214
+ const context = {
215
+ command: env.command,
216
+ mode: env.mode
217
+ };
218
+ const packageInfo = readPackageInfo(resolveProjectRoot(userConfig.root));
219
+ payload = createPayload(options, context, data, timeZone, packageInfo);
220
+ }
221
+ if (!defineName || !payload) {
222
+ return void 0;
223
+ }
224
+ return {
225
+ define: {
226
+ [defineName]: JSON.stringify(payload)
227
+ }
228
+ };
229
+ },
196
230
  configResolved(config) {
197
231
  skipBundleEmit = Boolean(config.build.ssr) && !config.build.ssrEmitAssets;
198
232
  if (payload) {
package/dist/index.d.cts CHANGED
@@ -12,6 +12,7 @@ interface BuildVersionPayload {
12
12
  interface BuildVersionPluginOptions {
13
13
  filename?: string;
14
14
  globalName?: string;
15
+ defineName?: string | false;
15
16
  injectToHtml?: boolean;
16
17
  timeZone?: string;
17
18
  version?: string | number | ((ctx: BuildVersionContext) => string | number);
package/dist/index.d.ts CHANGED
@@ -12,6 +12,7 @@ interface BuildVersionPayload {
12
12
  interface BuildVersionPluginOptions {
13
13
  filename?: string;
14
14
  globalName?: string;
15
+ defineName?: string | false;
15
16
  injectToHtml?: boolean;
16
17
  timeZone?: string;
17
18
  version?: string | number | ((ctx: BuildVersionContext) => string | number);
package/dist/index.mjs CHANGED
@@ -1,9 +1,10 @@
1
1
  // src/index.ts
2
2
  import { existsSync, readFileSync } from "fs";
3
- import { dirname, join } from "path";
3
+ import { dirname, join, resolve } from "path";
4
4
  var PLUGIN_NAME = "vite-plugin-build-version-file";
5
5
  var DEFAULT_FILENAME = "version.json";
6
6
  var DEFAULT_GLOBAL_NAME = "__VERSION__";
7
+ var DEFAULT_DEFINE_NAME = "__VERSION__";
7
8
  var DEFAULT_TIME_ZONE = "Asia/Shanghai";
8
9
  function createDefaultVersion(command, timeZone) {
9
10
  if (command === "serve") {
@@ -45,6 +46,15 @@ function normalizeGlobalName(globalName) {
45
46
  }
46
47
  return globalName;
47
48
  }
49
+ function normalizeDefineName(defineName) {
50
+ if (defineName === false || defineName === void 0) {
51
+ return defineName ?? false;
52
+ }
53
+ if (!defineName.trim()) {
54
+ throw new Error(`[${PLUGIN_NAME}] "defineName" cannot be empty.`);
55
+ }
56
+ return defineName;
57
+ }
48
58
  function normalizeTimeZone(timeZone) {
49
59
  const normalized = timeZone.trim();
50
60
  if (!normalized) {
@@ -129,6 +139,9 @@ function toRequestPath(base, fileName) {
129
139
  const baseWithoutTrailingSlash = withLeadingSlash.endsWith("/") ? withLeadingSlash.slice(0, -1) : withLeadingSlash;
130
140
  return `${baseWithoutTrailingSlash}/${fileName}`.replace(/\/{2,}/g, "/");
131
141
  }
142
+ function resolveProjectRoot(root) {
143
+ return root ? resolve(process.cwd(), root) : process.cwd();
144
+ }
132
145
  function resolveVersion(options, context, timeZone) {
133
146
  if (typeof options.version === "function") {
134
147
  return options.version(context);
@@ -155,6 +168,9 @@ function buildVersionPlugin(options = {}) {
155
168
  const globalName = normalizeGlobalName(
156
169
  options.globalName ?? DEFAULT_GLOBAL_NAME
157
170
  );
171
+ const defineName = normalizeDefineName(
172
+ options.defineName ?? DEFAULT_DEFINE_NAME
173
+ );
158
174
  const injectToHtml = options.injectToHtml ?? true;
159
175
  const timeZone = normalizeTimeZone(options.timeZone ?? DEFAULT_TIME_ZONE);
160
176
  const data = normalizeData(options.data);
@@ -168,6 +184,24 @@ function buildVersionPlugin(options = {}) {
168
184
  };
169
185
  const plugin = {
170
186
  name: PLUGIN_NAME,
187
+ config(userConfig, env) {
188
+ if (!payload) {
189
+ const context = {
190
+ command: env.command,
191
+ mode: env.mode
192
+ };
193
+ const packageInfo = readPackageInfo(resolveProjectRoot(userConfig.root));
194
+ payload = createPayload(options, context, data, timeZone, packageInfo);
195
+ }
196
+ if (!defineName || !payload) {
197
+ return void 0;
198
+ }
199
+ return {
200
+ define: {
201
+ [defineName]: JSON.stringify(payload)
202
+ }
203
+ };
204
+ },
171
205
  configResolved(config) {
172
206
  skipBundleEmit = Boolean(config.build.ssr) && !config.build.ssrEmitAssets;
173
207
  if (payload) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-plugin-build-version-file",
3
- "version": "0.1.11",
3
+ "version": "0.1.13",
4
4
  "description": "A Vite plugin that emits version.json and injects version metadata into HTML.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -13,6 +13,11 @@
13
13
  "types": "./dist/index.d.ts",
14
14
  "import": "./dist/index.mjs",
15
15
  "require": "./dist/index.cjs"
16
+ },
17
+ "./client": {
18
+ "types": "./dist/client.d.ts",
19
+ "import": "./dist/client.mjs",
20
+ "require": "./dist/client.cjs"
16
21
  }
17
22
  },
18
23
  "files": [