vite-plugin-build-version-file 0.1.0 → 0.1.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/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # vite-plugin-build-version
1
+ # vite-plugin-build-version-file
2
2
 
3
3
  一个面向 `Vue 3 + Vite` 的构建版本插件。
4
4
 
@@ -6,6 +6,7 @@
6
6
 
7
7
  - 构建产物中生成 `version.json`
8
8
  - 可选地向 HTML 注入 `window["__VERSION__"]`
9
+ - 通过 `import.meta.env.__VERSION__` 在代码中直接读取版本号
9
10
  - 支持自定义版本号、文件名和全局变量名
10
11
 
11
12
  适合用在这些场景:
@@ -24,13 +25,13 @@
24
25
  ## 安装
25
26
 
26
27
  ```bash
27
- pnpm add vite-plugin-build-version
28
+ pnpm add vite-plugin-build-version-file
28
29
  ```
29
30
 
30
31
  也可以使用:
31
32
 
32
33
  ```bash
33
- npm install vite-plugin-build-version
34
+ npm install vite-plugin-build-version-file
34
35
  ```
35
36
 
36
37
  ## 快速开始
@@ -38,7 +39,7 @@ npm install vite-plugin-build-version
38
39
  ```ts
39
40
  import { defineConfig } from 'vite'
40
41
  import vue from '@vitejs/plugin-vue'
41
- import buildVersionPlugin from 'vite-plugin-build-version'
42
+ import buildVersionPlugin from 'vite-plugin-build-version-file'
42
43
 
43
44
  export default defineConfig({
44
45
  plugins: [vue(), buildVersionPlugin()]
@@ -148,7 +149,7 @@ type BuildVersionPluginOptions = {
148
149
  ```ts
149
150
  import { defineConfig } from 'vite'
150
151
  import vue from '@vitejs/plugin-vue'
151
- import buildVersionPlugin from 'vite-plugin-build-version'
152
+ import buildVersionPlugin from 'vite-plugin-build-version-file'
152
153
 
153
154
  export default defineConfig({
154
155
  plugins: [vue(), buildVersionPlugin()]
@@ -160,7 +161,7 @@ export default defineConfig({
160
161
  ```ts
161
162
  import { defineConfig } from 'vite'
162
163
  import vue from '@vitejs/plugin-vue'
163
- import buildVersionPlugin from 'vite-plugin-build-version'
164
+ import buildVersionPlugin from 'vite-plugin-build-version-file'
164
165
 
165
166
  export default defineConfig({
166
167
  plugins: [
@@ -183,7 +184,7 @@ const version = window['__APP_VERSION__']
183
184
  ```ts
184
185
  import { defineConfig } from 'vite'
185
186
  import vue from '@vitejs/plugin-vue'
186
- import buildVersionPlugin from 'vite-plugin-build-version'
187
+ import buildVersionPlugin from 'vite-plugin-build-version-file'
187
188
 
188
189
  export default defineConfig({
189
190
  plugins: [
@@ -200,7 +201,7 @@ export default defineConfig({
200
201
  ```ts
201
202
  import { defineConfig } from 'vite'
202
203
  import vue from '@vitejs/plugin-vue'
203
- import buildVersionPlugin from 'vite-plugin-build-version'
204
+ import buildVersionPlugin from 'vite-plugin-build-version-file'
204
205
 
205
206
  export default defineConfig({
206
207
  plugins: [
@@ -223,7 +224,7 @@ dist/meta/version.json
223
224
  ```ts
224
225
  import { defineConfig } from 'vite'
225
226
  import vue from '@vitejs/plugin-vue'
226
- import buildVersionPlugin from 'vite-plugin-build-version'
227
+ import buildVersionPlugin from 'vite-plugin-build-version-file'
227
228
 
228
229
  export default defineConfig({
229
230
  plugins: [
@@ -243,13 +244,44 @@ export default defineConfig({
243
244
 
244
245
  ## 在项目中读取版本
245
246
 
246
- ### 读取注入的全局变量
247
+ 插件提供三种方式读取版本号,可根据场景选择:
248
+
249
+ ### 方式一:通过 `import.meta.env` 读取(推荐)
250
+
251
+ 版本号会被注入到 `import.meta.env` 中,可以直接在代码中使用:
252
+
253
+ ```ts
254
+ const version = import.meta.env.__VERSION__
255
+ console.log(version) // '20260401153045' 或 '1.2.3'
256
+ ```
257
+
258
+ **优势:**
259
+ - 无需等待页面加载或发起请求
260
+ - 类型安全,可在 `vite-env.d.ts` 中声明类型
261
+ - 适合在应用初始化时读取版本
262
+
263
+ **TypeScript 类型声明:**
264
+
265
+ ```ts
266
+ // vite-env.d.ts
267
+ interface ImportMetaEnv {
268
+ readonly __VERSION__: string
269
+ }
270
+
271
+ interface ImportMeta {
272
+ readonly env: ImportMetaEnv
273
+ }
274
+ ```
275
+
276
+ ### 方式二:读取注入的全局变量
247
277
 
248
278
  ```ts
249
279
  const version = window['__VERSION__']
250
280
  ```
251
281
 
252
- ### 读取 `version.json`
282
+ **说明:** 需要确保 `injectToHtml` 为 `true`(默认值)
283
+
284
+ ### 方式三:读取 `version.json`
253
285
 
254
286
  ```ts
255
287
  const response = await fetch('/version.json')
package/dist/index.cjs CHANGED
@@ -24,10 +24,14 @@ __export(index_exports, {
24
24
  default: () => index_default
25
25
  });
26
26
  module.exports = __toCommonJS(index_exports);
27
- var PLUGIN_NAME = "vite-plugin-build-version";
27
+ var PLUGIN_NAME = "vite-plugin-build-version-file";
28
28
  var DEFAULT_FILENAME = "version.json";
29
29
  var DEFAULT_GLOBAL_NAME = "__VERSION__";
30
- function formatBuildTimestamp(date) {
30
+ function createDefaultVersion(command) {
31
+ if (command === "serve") {
32
+ return 0;
33
+ }
34
+ const date = /* @__PURE__ */ new Date();
31
35
  const pad = (value) => value.toString().padStart(2, "0");
32
36
  return [
33
37
  date.getFullYear(),
@@ -38,12 +42,6 @@ function formatBuildTimestamp(date) {
38
42
  pad(date.getSeconds())
39
43
  ].join("");
40
44
  }
41
- function createDefaultVersion(command) {
42
- if (command === "serve") {
43
- return 0;
44
- }
45
- return formatBuildTimestamp(/* @__PURE__ */ new Date());
46
- }
47
45
  function normalizeFileName(filename) {
48
46
  const normalized = filename.replace(/\\/g, "/").replace(/^\/+/, "");
49
47
  if (!normalized || normalized.endsWith("/")) {
@@ -57,28 +55,6 @@ function normalizeGlobalName(globalName) {
57
55
  }
58
56
  return globalName;
59
57
  }
60
- function ensureVersionValue(value) {
61
- if (typeof value === "string" || typeof value === "number") {
62
- return value;
63
- }
64
- throw new Error(
65
- `[${PLUGIN_NAME}] "version" must resolve to a string or number.`
66
- );
67
- }
68
- function resolveVersionValue(versionOption, context) {
69
- if (versionOption === void 0) {
70
- return createDefaultVersion(context.command);
71
- }
72
- if (typeof versionOption !== "function") {
73
- return ensureVersionValue(versionOption);
74
- }
75
- try {
76
- return ensureVersionValue(versionOption(context));
77
- } catch (error) {
78
- const message = error instanceof Error ? error.message : String(error);
79
- throw new Error(`[${PLUGIN_NAME}] Failed to resolve version: ${message}`);
80
- }
81
- }
82
58
  function serializePayload(payload) {
83
59
  return `${JSON.stringify(payload, null, 2)}
84
60
  `;
@@ -104,15 +80,45 @@ function buildVersionPlugin(options = {}) {
104
80
  let payload;
105
81
  return {
106
82
  name: PLUGIN_NAME,
83
+ config(config, { command }) {
84
+ const context = {
85
+ command,
86
+ mode: config.mode || "development"
87
+ };
88
+ let version;
89
+ if (typeof options.version === "function") {
90
+ version = options.version(context);
91
+ } else if (options.version !== void 0) {
92
+ version = options.version;
93
+ } else {
94
+ version = createDefaultVersion(context.command);
95
+ }
96
+ return {
97
+ define: {
98
+ [`import.meta.env.${globalName}`]: JSON.stringify(version)
99
+ }
100
+ };
101
+ },
107
102
  configResolved(config) {
108
103
  const context = {
109
104
  command: config.command,
110
105
  mode: config.mode
111
106
  };
107
+ let version;
108
+ if (typeof options.version === "function") {
109
+ version = options.version(context);
110
+ } else if (options.version !== void 0) {
111
+ version = options.version;
112
+ } else {
113
+ version = createDefaultVersion(context.command);
114
+ }
112
115
  payload = {
113
- version: resolveVersionValue(options.version, context),
116
+ version,
114
117
  production: config.command === "build"
115
118
  };
119
+ if (options.payload) {
120
+ payload = options.payload(payload);
121
+ }
116
122
  },
117
123
  configureServer(server) {
118
124
  const requestPath = toRequestPath(server.config.base, fileName);
@@ -140,7 +146,7 @@ function buildVersionPlugin(options = {}) {
140
146
  {
141
147
  tag: "script",
142
148
  injectTo: "head",
143
- children: `window[${JSON.stringify(globalName)}] = ${JSON.stringify(payload.version)};`
149
+ children: `window[${JSON.stringify(globalName)}] = ${JSON.stringify(payload)};`
144
150
  }
145
151
  ];
146
152
  return tags;
@@ -154,6 +160,12 @@ function buildVersionPlugin(options = {}) {
154
160
  fileName,
155
161
  source: serializePayload(payload)
156
162
  });
163
+ if (options.log) {
164
+ console.log(options.log(payload));
165
+ } else {
166
+ console.log("[vite-plugin-build-version-file][build finished]");
167
+ console.log(serializePayload(payload));
168
+ }
157
169
  }
158
170
  };
159
171
  }
package/dist/index.d.cts CHANGED
@@ -13,6 +13,8 @@ interface BuildVersionPluginOptions {
13
13
  globalName?: string;
14
14
  injectToHtml?: boolean;
15
15
  version?: string | number | ((ctx: BuildVersionContext) => string | number);
16
+ log?: (content: any) => string;
17
+ payload?: (json: any) => any;
16
18
  }
17
19
  declare function buildVersionPlugin(options?: BuildVersionPluginOptions): Plugin;
18
20
 
package/dist/index.d.ts CHANGED
@@ -13,6 +13,8 @@ interface BuildVersionPluginOptions {
13
13
  globalName?: string;
14
14
  injectToHtml?: boolean;
15
15
  version?: string | number | ((ctx: BuildVersionContext) => string | number);
16
+ log?: (content: any) => string;
17
+ payload?: (json: any) => any;
16
18
  }
17
19
  declare function buildVersionPlugin(options?: BuildVersionPluginOptions): Plugin;
18
20
 
package/dist/index.mjs CHANGED
@@ -1,8 +1,12 @@
1
1
  // src/index.ts
2
- var PLUGIN_NAME = "vite-plugin-build-version";
2
+ var PLUGIN_NAME = "vite-plugin-build-version-file";
3
3
  var DEFAULT_FILENAME = "version.json";
4
4
  var DEFAULT_GLOBAL_NAME = "__VERSION__";
5
- function formatBuildTimestamp(date) {
5
+ function createDefaultVersion(command) {
6
+ if (command === "serve") {
7
+ return 0;
8
+ }
9
+ const date = /* @__PURE__ */ new Date();
6
10
  const pad = (value) => value.toString().padStart(2, "0");
7
11
  return [
8
12
  date.getFullYear(),
@@ -13,12 +17,6 @@ function formatBuildTimestamp(date) {
13
17
  pad(date.getSeconds())
14
18
  ].join("");
15
19
  }
16
- function createDefaultVersion(command) {
17
- if (command === "serve") {
18
- return 0;
19
- }
20
- return formatBuildTimestamp(/* @__PURE__ */ new Date());
21
- }
22
20
  function normalizeFileName(filename) {
23
21
  const normalized = filename.replace(/\\/g, "/").replace(/^\/+/, "");
24
22
  if (!normalized || normalized.endsWith("/")) {
@@ -32,28 +30,6 @@ function normalizeGlobalName(globalName) {
32
30
  }
33
31
  return globalName;
34
32
  }
35
- function ensureVersionValue(value) {
36
- if (typeof value === "string" || typeof value === "number") {
37
- return value;
38
- }
39
- throw new Error(
40
- `[${PLUGIN_NAME}] "version" must resolve to a string or number.`
41
- );
42
- }
43
- function resolveVersionValue(versionOption, context) {
44
- if (versionOption === void 0) {
45
- return createDefaultVersion(context.command);
46
- }
47
- if (typeof versionOption !== "function") {
48
- return ensureVersionValue(versionOption);
49
- }
50
- try {
51
- return ensureVersionValue(versionOption(context));
52
- } catch (error) {
53
- const message = error instanceof Error ? error.message : String(error);
54
- throw new Error(`[${PLUGIN_NAME}] Failed to resolve version: ${message}`);
55
- }
56
- }
57
33
  function serializePayload(payload) {
58
34
  return `${JSON.stringify(payload, null, 2)}
59
35
  `;
@@ -79,15 +55,45 @@ function buildVersionPlugin(options = {}) {
79
55
  let payload;
80
56
  return {
81
57
  name: PLUGIN_NAME,
58
+ config(config, { command }) {
59
+ const context = {
60
+ command,
61
+ mode: config.mode || "development"
62
+ };
63
+ let version;
64
+ if (typeof options.version === "function") {
65
+ version = options.version(context);
66
+ } else if (options.version !== void 0) {
67
+ version = options.version;
68
+ } else {
69
+ version = createDefaultVersion(context.command);
70
+ }
71
+ return {
72
+ define: {
73
+ [`import.meta.env.${globalName}`]: JSON.stringify(version)
74
+ }
75
+ };
76
+ },
82
77
  configResolved(config) {
83
78
  const context = {
84
79
  command: config.command,
85
80
  mode: config.mode
86
81
  };
82
+ let version;
83
+ if (typeof options.version === "function") {
84
+ version = options.version(context);
85
+ } else if (options.version !== void 0) {
86
+ version = options.version;
87
+ } else {
88
+ version = createDefaultVersion(context.command);
89
+ }
87
90
  payload = {
88
- version: resolveVersionValue(options.version, context),
91
+ version,
89
92
  production: config.command === "build"
90
93
  };
94
+ if (options.payload) {
95
+ payload = options.payload(payload);
96
+ }
91
97
  },
92
98
  configureServer(server) {
93
99
  const requestPath = toRequestPath(server.config.base, fileName);
@@ -115,7 +121,7 @@ function buildVersionPlugin(options = {}) {
115
121
  {
116
122
  tag: "script",
117
123
  injectTo: "head",
118
- children: `window[${JSON.stringify(globalName)}] = ${JSON.stringify(payload.version)};`
124
+ children: `window[${JSON.stringify(globalName)}] = ${JSON.stringify(payload)};`
119
125
  }
120
126
  ];
121
127
  return tags;
@@ -129,6 +135,12 @@ function buildVersionPlugin(options = {}) {
129
135
  fileName,
130
136
  source: serializePayload(payload)
131
137
  });
138
+ if (options.log) {
139
+ console.log(options.log(payload));
140
+ } else {
141
+ console.log("[vite-plugin-build-version-file][build finished]");
142
+ console.log(serializePayload(payload));
143
+ }
132
144
  }
133
145
  };
134
146
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-plugin-build-version-file",
3
- "version": "0.1.0",
3
+ "version": "0.1.3",
4
4
  "description": "A Vite plugin that emits version.json and injects version metadata into HTML.",
5
5
  "license": "MIT",
6
6
  "type": "module",