Best way to integrate Browserify into Cordova

1k Views Asked by At

I was trying to integrate Browserify into Cordova. I did the following:

  • Installed Browserify:
    npm install -g browserify
  • Moved index.js into the root:
    mv www/js/index.js .
  • Created a hook script named appBeforeBuild.sh which turns index.js into bundle.js:
    browserify index.js -o www/js/bundle.js
    EDIT - Please see my answer below
  • Updated config.xml to run the hook:
    <hook src="appBeforeBuild.sh" type="before_build" />
  • Updated index.html to include bundle.js instead of index.js:
    <script type="text/javascript" src="js/bundle.js"></script>

This could be a nice guide for integrating Browserify into Cordova, but unfortunately it is not working, because editing 'index.js' does not trigger a recompile.

Could anybody please explain how to set index.js into a file which is checked for the build dependencies and triggers the before_build hook?

1

There are 1 best solutions below

0
On

The check list in my question is just fine for integrating Browserify into Cordova, but the [before_build] script should be corrected. The following is a script suitable for Mac OSX:

File: appBeforeBuild.sh

echo "[before_build] Start"
b=$(stat -f "%Sm" -t "%Y%m%dT%H%M%S" index.js)
if [ -f timestamp_indexjs.txt ]; then
    a=$(cat timestamp_indexjs.txt)
    if [ $a == $b ]; then
        echo "- No change in index.js"
    else
        echo "- Calling Browserify (timestamp was changed)"
        echo $b>timestamp_indexjs.txt
        browserify index.js -o www/js/bundle.js
    fi
else
    echo "- Calling Browserify (First run, no timestamp)"
    echo $b>timestamp_indexjs.txt
    browserify index.js -o www/js/bundle.js
fi
echo "[before_build] End"

This file must be granted with execution rights:

chmod +x appBeforeBuild.sh

The idea in this script is to make sure that Browserify is called only when index.js was changed.

TIPS:

  • Put timestamp_indexjs.txt into your .gitignore file.
  • When investigating Cordova issues, run it with -d option, as in cordova -d build android