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?