Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

With create-react-app one could use process.env.REACT_APP_VERSION for this.

Is there an equivalent in Vite?

like image 914
Obiwahn Avatar asked Dec 10 '22 23:12

Obiwahn


2 Answers

If you want to use plugin, see Adarsh's answer

But it's very easy to implement it yourself. You can use define in vite.config.js. Read about it here

vite.config.js

export default {
    plugins: [vue()],
    define: {
        '__APP_VERSION__': JSON.stringify(process.env.npm_package_version),
    }
}

component.vue

<template>
    <div>{{ version }}</div>
</template>
<script>
export default {
    data () {
        version: __APP_VERSION__
    },
}
</script>

or with <script setup>

<script setup>
const version = __APP_VERSION__
</script>
<template>
    <div>{{ version }}</div>
</template>

You should be able to change '__APP_VERSION__' as long as it doesn't conflict with javascript syntax or other variables.

like image 190
Christhofer Natalius Avatar answered Feb 05 '23 14:02

Christhofer Natalius


For React & TypeScript users:

Add a define to your vite.config.ts:

import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [react()],
  define: {
    APP_VERSION: JSON.stringify(process.env.npm_package_version),
  },
});

If you haven't got one already, define a vite-env.d.ts or env.d.ts and add a declare:

declare const APP_VERSION: string;

You'll now be able to use the variable APP_VERSION anywhere in your code & Vite will substitute it at compile time.

Note: You may need to restart your TS server for the declaration to be picked up by intellisense:

VSCode MacOS: + + P > Restart TS Server

VSCode Windows: ctrl + + P > Restart TS Server

like image 26
Jamie Avatar answered Feb 05 '23 14:02

Jamie