vite-plugin-build-version-file 0.1.2 → 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 +34 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -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
|
适合用在这些场景:
|
|
@@ -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
|
-
|
|
282
|
+
**说明:** 需要确保 `injectToHtml` 为 `true`(默认值)
|
|
283
|
+
|
|
284
|
+
### 方式三:读取 `version.json`
|
|
253
285
|
|
|
254
286
|
```ts
|
|
255
287
|
const response = await fetch('/version.json')
|