EDIT: now the simplest solution is this:https://stackoverflow.com/a/65476892/1243247
Manual way
I made a functional hook script which I stored at hooks/setVersion.js
. I just tested it now and it works (just in Android, for iOS you just need to replicate the wwwDir
)
#!/usr/bin/env node
var wwwFileToReplace = 'index.html'
var fs = require('fs')
var path = require('path')
module.exports = function (context) {
var projectRoot = context.opts.projectRoot
const wwwDir = path.join(projectRoot, 'platforms', 'android', 'app', 'src', 'main', 'assets', 'www')
var configXMLPath = 'config.xml'
loadConfigXMLDoc(configXMLPath, (rawJSON) => {
var version = rawJSON.widget.$.version
console.log('Version:', version)
var fullfilename = path.join(wwwDir, wwwFileToReplace)
if (fs.existsSync(fullfilename)) {
replaceStringInFile(fullfilename, '%%VERSION%%', version)
console.log(context.hook + ': Replaced version in file: ' + path.relative(projectRoot, fullfilename))
} else {
console.error('File does not exist: ', path.relative(projectRoot, fullfilename))
process.exit(1)
}
})
}
function loadConfigXMLDoc (filePath, callback) {
var fs = require('fs')
var xml2js = require('xml2js')
try {
var fileData = fs.readFileSync(filePath, 'ascii')
var parser = new xml2js.Parser()
parser.parseString(fileData.substring(0, fileData.length), function (err, result) {
if (err) {
console.error(err)
process.exit(1)
} else {
// console.log("config.xml as JSON", JSON.stringify(result, null, 2))
console.log("File '" + filePath + "' was successfully read.")
callback(result)
}
})
} catch (ex) {
console.log(ex)
process.exit(1)
}
}
function replaceStringInFile (filename, toReplace, replaceWith) {
var data = fs.readFileSync(filename, 'utf8')
var result = data.replace(new RegExp(toReplace, 'g'), replaceWith)
fs.writeFileSync(filename, result, 'utf8')
}
You have also to add in config.xml
<hook src="hooks/setVersion.js" type="after_prepare"/>
This script replaces the text %%VERSION%%
in a file with the app version from config.xml, so you can have in your index.html
file something like
<html data-appversion="%%VERSION%%">
and in your JS
const version = document.documentElement.getAttribute("data-appversion");