SoFunction
Updated on 2025-04-12

Implementation method of automatically updating version number when vue project is packaged

Preface

The current version number will be displayed on the page. It will be troublesome to manually change the version number every time you update. Now, the version number will be automatically updated every time npm run build, and the update rules will be defined by yourself.

TODO: There is no distinction between development environment, testing environment, and formal environment

Create an automatic update version script

Create in the root directoryScript File

const fs = require('fs')
const path = require('path')

// Read the version number inconst packageJsonPath = (__dirname, '')
const packageJson = ((packageJsonPath, 'utf-8'))
let version = 

// Split version number and incrementlet [major, minor, patch] = ('.').map(Number)

patch++ // Increment patch version number// if (patch >= 10) {
// 	patch = 0
// 	minor++
// 	if (minor >= 10) {
// 		minor = 0
// 		major++
// 	}
// }

// Update version numberversion = `${major}.${minor}.${patch}`

// Define the content of the environment variable. If there are other configurations in .env, you should write them together.const envContent = `VITE_APP_VERSION = ${version}`

// Write to .env fileconst envPath = (__dirname, '.env')
(envPath, envContent, 'utf-8')
// Updated version number = version

// Write the updated file back to the file(packageJsonPath, (packageJson, null, 2), 'utf-8')

(`Updated version number to: ${version}`)

Page to get version number

Use directly where version number is required

const version = .VITE_APP_VERSION

Modify configuration

Modify build packaging and add autoVersion

    "build": "npm run autoVersion && vite build",
    "autoVersion": "node "

This is the article about the implementation method of automatically updating the version number when packaging vue projects. For more related contents for automatically updating the version number when packaging vue, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!