Vue-CLI 版本号 - 它是否存在以及如何在 Vue 应用程序本身中使用它?

问题描述 投票:0回答:1

我正在使用 Vue CLI 构建一个用于生产部署的 Vue 应用程序。

我想在应用程序中包含一个典型的递增版本号,以便我和测试人员可以确保我们正在测试正确的版本。我想在应用程序中至少以两种方式使用它:a)将其显示给测试人员,b)将其包含在错误跟踪 API 调用中,例如前往 Sentry.io。

目前我必须查看 app.XXXX.js 上的哈希值并进行比较。虽然这确实唯一地标识了构建,但它不是连续的,对于 CSS/JS/供应商等来说是不同的,并且很难在代码库中使用。

我很高兴编写一个构建包装脚本来管理数字并将其注入到构建中(如果需要的话)。

我当前使用的命令是例如

npx vue-cli-service build --mode staging
vue.js testing build versioning vue-cli
1个回答
1
投票

我已经使用日期和时间实现了一些东西。它位于 Vue 2 项目中。

将此代码(或类似的代码)添加到

vue.config.js
文件的顶部:

const verMajor = 1;
const verMinor = 0;
const now = new Date();
const padTwo = (val) => (val > 9 ? "" : "0") + val;
const nowMonth = now.getMonth() + 1;
const nowDay = now.getDate();
const verBuildDate = now.getFullYear() + padTwo(nowMonth) + padTwo(nowDay);
const verBuildTime = padTwo(now.getHours()) + padTwo(now.getMinutes()) + padTwo(now.getSeconds());
process.env.VUE_APP_VERSION = `${verMajor}.${verMinor}.${verBuildDate}.${verBuildTime}`;

console.log(`Building version: ${process.env.VUE_APP_VERSION}`);

//  ...rest of the config

在组件代码中,你可以这样做:

get versionText(): string {
    return process.env.VUE_APP_VERSION;
}

但是我正在使用基于类的组件,所以如果你不这样做,我想这会起作用:

computed: {
    versionText: funnction () {
        return process.env.VUE_APP_VERSION;
    }
}

在模板中:

Ver: {{versionText}}

这会导致类似的结果:

版本:1.0.20211013.110634

如果看起来太长,我确信可以根据您的需要缩短它 - 或者您可以在文件中存储一个数字并在配置文件中编写一些 JS 以在每个构建中递增它 - 或者每个发布构建,如果您检查

process.env.NODE_ENV === "release"

有关更多信息,请参阅:https://cli.vuejs.org/guide/mode-and-env.html

:o)

Vue 3

在 vite.config.ts 中,我有:

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import * as fs from "fs";

const packageJson = String(fs.readFileSync("./package.json"));
const packageData = JSON.parse(packageJson);
const packageVersionText = packageData.version || "0.0.0";
const versionText = doSomethingToAddBuildDateAndTimeOrSomething(packageVersionText);

export default defineConfig({
    plugins: [vue()],
    define: {
        "__APP_VERSION__": `"${versionText}"`
    },
    // rest of stuff...

在我们想要版本的组件中(我使用带有“setup”脚本的组合API):

<script lang="ts">
    declare const __APP_VERSION__: string; // see vite.config.ts
</script>
<script setup lang="ts">

    // componenty stuff...

    const versionNumber = `Version ${__APP_VERSION__}`;  // or whatever

    // more stuff...
© www.soinside.com 2019 - 2024. All rights reserved.