前言

hooks是一些在Cordova执行命令时运行的特殊脚本,能够允许你拓展Cordova命令来适应你自己的需求。官方推荐三个地方定义hooks,分别在工程的config.xml、插件的plugin.xml和hooks文件夹,这里介绍的是第三个地方。任何一门编程语言都能够写hooks,但是考虑到跨平台运行(即需要不同语言的运行环境),推荐使用Node.js。

一、hooks应用场景

hooks应用场景一:修改应用配置信息,我们在应用开发中,引入的插件可能有冲突之类的问题,这个时候原生开发人员会让我们在添加平台加一些配置信息。也就是说我们每次添加平台后都需要手动去改平台中代码,不太方便,程序员就要尽可能的懒起来,这个时候就可以用上hooks了;
hooks应用场景二:环境切换,我们的Cordova工程经常有开发、uat、生产等不同环境。对应不同的环境,我们有不同的接口地址、不同的插件API keys,甚至不同的应用图标和Splash。对于不同接口地址、不同的应用图标和Splash等,我们可以使用自定义gulp任务实现,但是对于插件中的接口地址、API keys不太好做处理。

二、Cordova支持的hooks类型:

Hook Type Associated Cordova Commands Description
before_platform_add cordova platform add To be executed before and after adding a platform.
after_platform_add
before_platform_rm cordova platform rm To be executed before and after removing a platform.
after_platform_rm
before_platform_ls cordova platform ls To be executed before and after listing the installed and available platforms.
after_platform_ls
before_prepare cordova prepare
cordova platform add
cordova build
cordova run
To be executed before and after preparing your application.
after_prepare
before_compile cordova compile
cordova build
To be executed before and after compiling your application.
after_compile
before_build cordova build To be executed before and after building your application.
after_build
before_emulate cordova emulate To be executed before and after emulating your application.
after_emulate
before_run cordova run To be executed before and after running your application.
after_run
before_serve cordova serve To be executed before and after serving your application.
after_serve
before_clean cordova clean To be executed before and after cleaning your application.
after_clean
pre_package N/A Applicable to Windows 8 and Windows Phone only. This hook is deprecated.
before_plugin_add cordova plugin add To be executed before and after adding a plugin.
after_plugin_add
before_plugin_rm cordova plugin rm To be executed before and after removing a plugin.
after_plugin_rm
before_plugin_ls cordova plugin ls To be executed before and after listing the plugins in your application.
after_plugin_ls
before_plugin_search cordova plugin search To be executed before and after a plugin search.
after_plugin_search
before_plugin_install cordova plugin add To be executed before and after installing a plugin (to the platforms). Plugin hooks in plugin.xml are executed for a plugin being installed only
after_plugin_install
before_plugin_uninstall cordova plugin rm To be executed before uninstalling a plugin (from the platforms).Plugin hooks in plugin.xml are executed for a plugin being installed only

三、hooks执行顺序

根据以上表格可以推导出不同类型hooks执行顺序,以cordova platform add和cordova build为例:

cordova platform add:before_platform_addbefore_prepareafter_preparebefore_plugin_installafter_plugin_installafter_platform_addcordova build:before_buildbefore_prepareafter_preparebefore_compileafter_compileafter_build

四、应用实例

4.1、以我现在正在开发的xxx项目为例,添加平台后修改平台内配置信息(cordova platform add)

1、在应用根目录下新建hooks文件夹(如果先前有可删除),在hooks文件夹内新建after_platform_add文件夹,内新建一个js文件,命名随意;
2、读写平台中的AndroidManifest.xml文件,修改配置信息
3、Android打包配置需求如下:

一、解决方法数越界
1.build.gradle 配置
defaultConfig{multiDexEnabled true
}
2.dependencies{compile "com.android.support:multidex:1.0.0"
}
3.AndroidManifest.xml 中Application添加属性
android:name="android.support.multidex.MultiDexApplication"二、解决条码扫描插件最低版本冲突
1.AndroidManifest.xml 中Manifest添加属性
xmlns:tools="http://schemas.android.com/tools"
2.Manifest中添加节点
<uses-sdk android:minSdkVersion="16" tools:overrideLibrary="org.xwalk.core" />

4、附上hooks源代码(xxx/after_platform_add/xxx.js):

var fs = require('fs');
var path = require('path');
var rootdir = process.argv[2];//正则表达式替换文本
function replace_string_in_file(filename, to_replace, replace_with) {var data = fs.readFileSync(filename, 'utf8');var result = data.replace(to_replace, replace_with);fs.writeFileSync(filename, result, 'utf8');
}if (rootdir) {//获取平台信息数组var platforms = (process.env.CORDOVA_PLATFORMS ? process.env.CORDOVA_PLATFORMS.split(',') : []);for (var x = 0; x < platforms.length; x += 1) {try {var platform = platforms[x].trim().toLowerCase();//如果是android平台if (platform === 'android') {//替换平台内AndroidManifest.xml文件内容var fullfilename = path.join(rootdir, ‘platforms/android/AndroidManifest.xml');//判断AndroidManifest.xml文件是否存在if (fs.existsSync(fullfilename)) {replace_string_in_file(fullfilename, "<manifest", '<manifest xmlns:tools="http://schemas.android.com/tools"');replace_string_in_file(fullfilename, "<supports-screens", '<uses-sdk android:minSdkVersion="16" tools:overrideLibrary="org.xwalk.core" /><supports-screens');replace_string_in_file(fullfilename, "<application", '<application android:name="android.support.multidex.MultiDexApplication"');} else {console.log("missing: " + fullfilename);}//替换build.gradle文件内容var fullfilename2 = path.join(rootdir, 'platforms/android/build.gradle');if (fs.existsSync(fullfilename2)) {replace_string_in_file(fullfilename2, /defaultConfig\s*\{/gi, 'defaultConfig {\n multiDexEnabled true');replace_string_in_file(fullfilename2, /}\s*dependencies\s*\{/gi, '}\n dependencies {\n compile "com.android.support:multidex:1.0.0"');} else {console.log("missing: " + fullfilename2);}}} catch (e) {process.stdout.write(e);}}
}

4.2、修改插件配置信息(这里修改xxx插件API_KEY为例)

1、在应用根目录下新建hooks文件夹(如果先前有可删除),在hooks文件夹内新建before_build和before_compile文件夹,内分别新建一个js文件,命令随意;
2、需求如下(需在原生开发人员配合下修改,由原生开发人员提出修改需求)

1、修改android平台内AndroidManifest.xml,配置RONG_CLOUD_APP_KEY(<meta-data android:name=“RONG_CLOUD_APP_KEY" android:value="" />)
2、修改ios平台的plist文件,配置参数(<config-file target="*LBXIMConfig.plist"  parent="RongCloudKey"><string>$RONGCLOUD_KEY</string></config-file>)

3、考虑到android在prepare中会添加到AndroidManifest.xml中,所以在before_build文件夹中写如下代码,删除相应配置信息,代码如下(xxx/before_build/xxx.js):

var fs = require('fs');
var path = require('path');
var rootdir = process.argv[2];function replace_string_in_file(filename, to_replace, replace_with) {var data = fs.readFileSync(filename, 'utf8');var result = data.replace(data.match(to_replace)[0], replace_with);fs.writeFileSync(filename, result, 'utf8');
}if (rootdir) {// go through each of the platform directories that have been preparedvar platforms = (process.env.CORDOVA_PLATFORMS ? process.env.CORDOVA_PLATFORMS.split(',') : []);for (var x = 0; x < platforms.length; x += 1) {try {var platform = platforms[x].trim().toLowerCase();if (platform === 'android') {//替换AndroidManifest.xml文件内容,删除RONG_CLOUD_APP_KEYvar fullfilename = path.join(rootdir, 'platforms/android/AndroidManifest.xml');replace_string_in_file(fullfilename, '<meta-data\.\*android:name="RONG_CLOUD_APP_KEY"\.\*\/>', '');}} catch (e) {process.stdout.write(e);}}
}

4、在平台编译之前加上参数。读取配置文件(自定义)内的RONG_CLOUD_APP_KEY,把参数信息写入平台内部的配置文件中(xxx/before_compile/xxx.js):

var fs = require('fs');
var path = require('path');
var rootdir = process.argv[2];
function replace_string_in_file(filename, to_replace, replace_with) {var data = fs.readFileSync(filename, 'utf8');var result = data.replace(data.match(to_replace)[0], replace_with);fs.writeFileSync(filename, result, 'utf8');
}
//获取应用名(因为在ios平台中plist配置文件在应用名文件夹目录下)
function get_data_in_configxmlfile(filename, to_replace) {var data = fs.readFileSync(filename, 'utf8');return data.match(to_replace)[1];
}
//替代plist文件内的配置信息
function replace_data_in_plistfile(filename, to_replace, replace_with) {var configPlist = fs.readFileSync(filename, 'utf8');var result = configPlist.replace(to_replace, replace_with);fs.writeFileSync(filename, result, 'utf8');
}if (rootdir) {// go through each of the platform directories that have been preparedvar platforms = (process.env.CORDOVA_PLATFORMS ? process.env.CORDOVA_PLATFORMS.split(',') : []);var ourConfigFile = path.join(rootdir, "app/config/config.json");if (fs.existsSync(ourConfigFile)) {var configObj = JSON.parse(fs.readFileSync(ourConfigFile, 'utf8'));} else {console.log("app/config/config.json not exist!!!");return;}for (var x = 0; x < platforms.length; x += 1) {try {var platform = platforms[x].trim().toLowerCase();if (platform === 'android') {//替换AndroidManifest.xml文件内容,配置RONG_CLOUD_APP_KEYvar fullfilename = path.join(rootdir, 'platforms/android/AndroidManifest.xml');replace_string_in_file(fullfilename, 'android:name="RONG_CLOUD_APP_KEY"\.\*\/>','android:name="RONG_CLOUD_APP_KEY" android:value="' + configObj["baseConfig"]["RONG_CLOUD_APP_KEY"] + '" />');} else {//添加config.xml,读取文件内的应用名var ourIosConfigFile = path.join(rootdir, "config.xml");//获取应用名var appName = get_data_in_configxmlfile(ourIosConfigFile, "<name>(\.\*)<\/name>");//修改im配置plist文件var imConfigFile = 'platforms/ios/' + appName + '/Resources/LBXIMConfig.plist';if (fs.existsSync(imConfigFile){replace_data_in_plistfile(imConfigFile, /<key>RongCloudKey<\/key>\s*<string>\s*\S*<\/string>/gi, '<key>RongCloudKey</key>\n\t<string>' + configObj["baseConfig"]["RONG_CLOUD_APP_KEY"] + '<\/string>');} }} catch (e) {process.stdout.write(e);}}
}

cordova之hooks相关推荐

  1. 转--深入LUA脚本语言,让你彻底明白调试原理

    [原创声明] 如果觉得文章不错,请转发.分享给您的朋友 我会把十多年嵌入式开发中的项目实战经验进行总结.分享,相信不会让你失望的! 转载:欢迎转载,但未经作者同意,必须保留此段声明,必须在文章中给出原 ...

  2. ionic中使用Cordova Uglify 压缩js与css

    参照:https://www.npmjs.com/package/cordova-uglify 安装:npm install cordova-uglify 安装完成之后,打开: hooks/uglif ...

  3. android支付宝插件,GitHub - DmcSDK/cordova.plugin.alipay: cordova 支付宝支付插件,支持IOS Android。...

    cordova.plugin.alipay cordova 支付宝支付插件 cordova plugin add https://github.com/DmcSDK/cordova.plugin.al ...

  4. Using the Cordova Camera API

    使用ionic开发一款android或ios应用,估计少不了使用到Camera API,这里记录下使用过程. 创建空的ionic应用 ionic start myTabs tabs 通过cd demo ...

  5. 新建android项目导包,Cordova开发App入门(一)创建android项目

    前言Apache Cordova是一个开源的移动开发框架.允许使用标准的web技术-HTML5,CSS3和JavaScript做跨平台开发. 应用在每个平台的具体执行被封装了起来,并依靠符合标准的AP ...

  6. cordova+vue 项目打包成Android(apk)应用

    现在使用vue开发的项目越来越多,使用vue开发的移动端打包就成了最大的问题. 现在前端打包方案有好多种,但是综合来说,我比较喜欢用cordova来进行Android和ios的打包,配置完成之后,每次 ...

  7. 通过cordova将vue项目打包成app

    准备工作包括nodejs.cordova.AndroidStudio. 一.创建一个cordova工程 cordova create cordovaVue cd cordovaVue config.x ...

  8. Cordova 快速入门记录

    本篇文章由:http://xinpure.com/cordova-quick-start-recording/ 记一笔 Cordova 官网入门文档 Get Started Fast,言简意该.通俗易 ...

  9. java安卓app开发教程_[Android教程] Cordova开发App入门(一)创建android项目

    前言 Apache Cordova是一个开源的移动开发框架.允许使用标准的web技术-HTML5,CSS3和JavaScript做跨平台开发. 应用在每个平台的具体执行被封装了起来,并依靠符合标准的A ...

最新文章

  1. 思科路由器MTU及ip tcp adjust-mss测试
  2. 嬴彻再融超亿美元,宁德时代领投,领跑自动驾驶卡车行业
  3. 成功解决利用pandas的read_csv函数读取csv文件的时候出现中文乱码问题
  4. 解决启动flanneld失败的方法
  5. CentOS7搭建hadoop2.6.4+HBase1.1.6
  6. dnf加物理攻击的卡片有哪些_DNF:节日宝珠之外百分比神器附魔,拍卖行100w,实用不氪金...
  7. Broker模块划分
  8. 怎样在Windows 2016 Hyper-V上创建虚拟机
  9. 基于SEIR的传播动力学模型
  10. 中职计算机教师试讲技巧,中职教师资格面试原来是这样考的的!
  11. Python爬虫:英雄联盟近期战绩查询
  12. 论二级域名收集的各种姿势
  13. 程序员高考试卷泄密,检查一下你能答对多少题?
  14. Jetson嵌入式系列模型部署-3
  15. (九)隐私计算--安全多方计算
  16. CNN卷积层神经元数量、连接数量、权重数量的计算
  17. Echarts-- 圆环图2.0
  18. mysql 本日、本周、本月、本年 统计
  19. 安徽省六安市谷歌卫星地图下载
  20. C#调用TSC条码打印机打印条码

热门文章

  1. Maven与IDEA版本兼容问题以及配置
  2. 计算机考研408每日一题 day95
  3. 【Three.js】雪花圣诞树
  4. sentinel 热点限流
  5. 《大学生前端成长记》 ---JavaScript基础 --冒泡(Bubble)和取消冒泡(cancelBubble)
  6. ObjectARX运行时类信息实现原理
  7. Windows下本地安装git客户端
  8. DigiCert SSL证书怎么样?
  9. Hystrix 服务熔断
  10. 【芯片前端】第一次看DC综合报告时看些什么内容