Search code examples
typescriptvuejs3versionpackage.jsonvite

How do I display the version number from package.json in my vue3 app?


I want to display the version number of my app, defined in package.json. I am using Vite, Vue 3, Typescript, and script setup with composition API.

I solved this exact problem I had, but I have too little reputation to answer this question:

How can I display the current app version from package.json to the user using Vite?

So here is how to do it in Vue 3.

Use this answer as a basis: https://stackoverflow.com/a/74860417/12008976.

So, add

import packageJson from "./package.json"

and

define: {
  'import.meta.env.PACKAGE_VERSION': JSON.stringify(packageJson.version),
},

to vite.config.ts

Add this

/// <reference types="vite/client" />

interface ImportMetaEnv {
  readonly PACKAGE_VERSION: string
}

interface ImportMeta {
  readonly env: ImportMetaEnv
}

to env.d.ts in /src

Now, this adds intellisense to import.meta.env. But you cannot use these import statements directly in a Vue component. I fixed it by using the globalProperties of the Vue app.

Add

app.config.globalProperties.versionNumber = import.meta.env.PACKAGE_VERSION

to main.ts

Now, in a component, add

<script setup lang="ts">
const version = getCurrentInstance()?.appContext.config.globalProperties.versionNumber
</script>
<div>{{ version }}</div>

My question is: is this the best way to solve this in Vue 3?


Solution

  • I was asking the same question, and most of the solutions were similar to what you have mentioned, but then I found this answer.

    Add new variable to your .env file:

    VITE_APP_VERSION=$npm_package_version
    

    and then you can use it in your app:

    const version = import.meta.env.VITE_APP_VERSION
    

    However I did not find any documentation on how the $npm_package_* variables work, but apparently they are automatically populated from your package.json file. If you find any resources, please add it here.