I managed to inject the script at build time.
First install gulp-inject ( npm install gulp-inject --save-dev )
Then add a placeholder in the src/index.html
<!-- inject:js -->
<!-- endinject -->
Then create a script that with inject the Branch.io JS in the index.html
Ex : browser.config.js
var gulp = require('gulp');
var inject = require('gulp-inject');
gulp.src('./www/index.html')
.pipe(inject(gulp.src(''), {
starttag: '<!-- inject:js -->',
transform: function () {
if (process.env.IONIC_TARGET !== 'cordova') {
return '<script>(function(b,r,a,n,c,h,_,s,d,k){if(!b[n]||!b[n]._q){for(;s<_.length;)c(h,_[s++]);d=r.createElement(a);d.async=1;d.src="https://cdn.branch.io/branch-latest.min.js";k=r.getElementsByTagName(a)[0];k.parentNode.insertBefore(d,k);b[n]=h}})(window,document,"script","branch",function(b,r){b[r]=function(){b._q.push([r,arguments])}},{_q:[],_v:1},"addListener applyCode autoAppIndex banner closeBanner closeJourney creditHistory credits data deepview deepviewCta first getCode init link logout redeem referrals removeListener sendSMS setBranchViewData setIdentity track validateCode trackCommerceEvent logEvent".split(" "), 0);</script>';
} else {
return '';
}
}
})).pipe(gulp.dest('./www'));
I found that the environment variable IONIC_TARGET is equal to “cordova” when building for Android or iOS (ex: ionic cordova build android --prod), and when building for a pwa IONIC_TARGET is undefined (ex: ionic build --prod).
For the script to be executed at build time we can override a ionic-app-script config file. To do that edit your package.json and add :
"config": {
"ionic_webpack": "./browser.config.js"
}
I used “ionic_webpack” because it’s executed after the “copy” task, which copy the index.html to “www/index.html”.
This method also work when using “ionic serve”