Search code examples
javascriptcordovaandroid-6.0-marshmallow

Javascript syntax error using Cordova in Android 6


I'm using Cordova and have a syntax error in Android API 23 (6 Marshmallow).
Everything works fine on API 28 (9 Pie) and API 21 (5 Lollipop) but with API 23, I have those errors :

Uncaught SyntaxError: Unexpected token =>
Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
Uncaught SyntaxError: missing ) after argument list

I'm using vanilla JS and nothing else.

What is the problem? And how could I solve it?


Solution

  • It appears that the problem come from an incompatibility of ES6 in API 23.
    To resolve this, I use babel.

    sudo npm install --save-dev @babel/preset-env

    Create a .babelrc file

    {
        "presets": ["@babel/preset-env"],
        "sourceType": "script" //To remove 'use strict' of generated js files
    }
    

    Then you can transcompile your code into es5 with this command
    npx babel src/js -d www/js

    It's possible to execute this command automaticaly with hooks. Just create a .sh file (for example build.sh) and add the command to it. Add the hook to the config.xml file
    <hook type="before_build" src="hooks/build.sh" />