在构建期间通过钩子编辑值 [英] Editing values during build via hooks
问题描述
我在构建应用程序时尝试编辑版本变量,但我根本无法使用 cordova 挂钩运行任何脚本.
Im trying to edit a version variable when I build my applications, but I can't get any scripts to run using the cordova hooks at all.
我想从 package.json 和 git 提交的最后 5 位获取版本,这样我就可以使用 1.0.0.89gkt 作为我的版本.
I want to get the version from the package.json and the last 5 digits of the git commit so i can have something like 1.0.0.89gkt as my versions.
在过去使用 ionic 1 并使用 grunt 或 gulp 时,我能够轻松地将脚本添加到构建过程中.
In the past for ionic 1 and using grunt or gulp I was able to add the scripts into the build process easily.
我已经尝试了使用 hooks/hook_name/script 格式和在 config.xml 中使用 hook 标记的旧方法,但对我都不起作用.
I've tried both the old way using the hooks/hook_name/script format and using the hook tag in the config.xml and neither work for me.
通过 package.json 覆盖离子脚本允许我更改自动运行的脚本,但如果可以的话,我想避免这种情况.虽然我可以轻松地将我的文本替换添加到一个复制脚本或其他东西(我需要找出哪个最好)
Overwriting the ionic scripts via the package.json allows me to change the scripts that are automatically run, but I want to avoid that if I can. Though I can easily add my text replace to one of the copy scripts or something (ill need to work out which one is best)
如果有人知道更好的方法或钩子无法触发的原因,请告诉我.
If someone knows a better way or a reason as to why the hooks wont fire, please let me know.
推荐答案
这是我最终使用的解决方案.
This is the solution that I ended up using.
脚本/before_prepare_increment_build_number.js
scripts/before_prepare_increment_build_number.js
var fs = require('fs');
var git = require('git-rev-sync')
console.log('Incrementing Build Number');
var file = fs.readFileSync('www/build/main.js', 'utf8');
var str = git.short();
console.log('short', str)
var result = file.replace(/{{GITVERSIONSTRING}}/g, str);
fs.writeFileSync('www/build/main.js', result);
console.log('Incrementing Build Number Completed');
config.xml
<hook src="scripts/before_prepare_increment_build_number.js" type="before_prepare"/>
我需要确保一切同步发生,否则内置脚本会在字符串被替换之前开始复制.
I needed to ensure that everything was happening synchronously otherwise the built in scripts would start copying before the strings had been replaced.
目前它的目标是由默认 ionic-app-scripts 生成的整个 main.js,因此可以根据需要添加所有比较和替换.此解决方案使用内置的 cordova 钩子 before_prepare
Currently its targeting the whole main.js that is generated by the default ionic-app-scripts so all comparisons and replacements can be added as required.
This solution uses the built in cordova hook before_prepare
另一个提高效率的解决方案是根据需要定位单个文件,并在 package.json 中的构建/服务脚本之前添加脚本,并让 npm 控制和管理它.
Another solution that can be used to make it a bit more efficient is targeting the individual files as required and adding the script before the build/serve scripts in the package.json and have npm control and manage it.
在您的 package.json 中,您可以将脚本添加到准备钩子中.
Inside your package.json you could add a script to a prepare hook.
"scripts": {
"prepare": "node increment_build_number.js",
}
这篇关于在构建期间通过钩子编辑值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!