Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Babel JS babel-preset-php error

I was just trying the new Babel's babel-preset-php (https://gitlab.com/kornelski/babel-preset-php#php7-to-es7-syntax-translator). I did everything in the README file, I installed the preset with npm i -S babel-preset-php. Then I created a .babelrc file with the following contents;

{
    "presets": ["php"]
}

Installed the cli with npm i -g babel-cli. Then I created a simple PHP file that only contains a simple function:

<?php

function addCalculator($x, $y)
{
    return $x + $y;
}

And tried to run the transpiler with babel number.php -o file.js. But I get an error in the execution of the script:

/home/claudio/Documents/Development/babel/node_modules/babel-preset-php/lib/plugins.js:6
        Identifier(p) {
                  ^
SyntaxError: Unexpected token ( (While processing preset: "/home/claudio/Documents/Development/babel/node_modules/babel-preset-php/index.js")
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/home/claudio/Documents/Development/babel/node_modules/babel-preset-php/index.js:1:79)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)

I'm not that experient with nodejs and npm, so any idea on what might be happening?

like image 275
Cláudio Ribeiro Avatar asked Jul 15 '17 16:07

Cláudio Ribeiro


2 Answers

Edit: Ok, I just realized that you are calling a public function outside of a class. That's not correct PHP. You can't define a function as public outside of a class. Your PHP code is just wrong.

like image 54
Armin Šupuk Avatar answered Oct 14 '22 08:10

Armin Šupuk


The error is being emitted before it even touches your PHP code. It is, in fact, erroring on this particular line of babel-preset-php itself:

return {
    visitor: {
        Identifier(p) { // This is the invalid line
            if (p.node.name != 'Exception' || p.scope.hasBinding("Exception")) {
                return;
            }

This preset is using the shorthand object initializers added in ECMAScript 2015. What is probably happening here is that your local Javascript environment does not support ES2015 syntax.

I would recommend updating node and babel to the latest versions and trying again.

like image 21
Ben Visness Avatar answered Oct 14 '22 08:10

Ben Visness