-
Import the package.json file
In a Vite project, you can directly import the package.json file to retrieve version information. Since Vite supports importing JSON files, you can import it just like a JavaScript module.
javascriptimport packageInfo from '../package.json'; -
Make version information accessible in your code
Define a variable to access the version information and ensure it's available in the context where you need to display it.
javascriptconst { version } = packageInfo; -
Display version information in the UI
In React, use this variable in your component as follows:
jsxfunction App() { return ( <div> <p>Current version: {version}</p> </div> ); }In Vue, include it in the data or computed properties:
vue<template> <div> <p>Current version: {{ version }}</p> </div> </template> <script> export default { data() { return { version: packageInfo.version }; } } </script> -
Build and deploy
After committing the code and passing tests, deploy it to production. With Vite, it replaces the version number from package.json in the bundled code during the build process.
-
Example: Displaying the version in a Vite project
Suppose you have a Vite+React project and wish to display the current version number at the bottom of the page.
jsx// src/components/Footer.js import React from 'react'; import packageInfo from '../../package.json'; const Footer = () => ( <footer> <span>© 2023 MyCompany</span> <span>Version: {packageInfo.version}</span> </footer> ); export default Footer;This will display the current application version in the Footer component.
Note that embedding the version number in client-side code may reveal your application's update cycle, which is a security consideration. If the version information includes sensitive data or dependency versions, it's advisable not to expose it fully to the client. During deployment, consider a more secure method to display this information.