Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SAFARI : Unexpected token '='. Expected an opening '(' before a method's parameter list

Got this code, that works perfectly in all browsers but not in Safari (Version 11.1.2).

class Account {
 accountFields = ['field1', 'field2', 'field3']
}

Getting the following error in Safari debugger:

Unexpected token '='. Expected an opening '(' before a method's parameter list

So I tried to add () everywhere, around the array, before, after, etc. Nothing works.

like image 749
Simon Mo Avatar asked Feb 02 '20 13:02

Simon Mo


1 Answers

You're using an experimental feature known as public field declarations which is currently in stage 3. The only Safari versions that support this feature are v14.1 (released April 26th, 2021) and higher. If you need to support older versions of Safari / a wider variety of browsers you'll need to follow one of the suggestions below.


Instead of using public field declarations, you can use a constructor() method to define the properties for your class instances. Using a constructor does have good browser compatibility (for IE support you can use a constructor function):

class Account {
  constructor() {
    this.accountFields = ['field1', 'field2', 'field3'];
  }
}

As pointed out in the comments by @Baz, you can also use Babel as an alternative solution. Using babel means that you won't have to change your code, which can make things easier on you if you're using public field declarations a lot throughout your project. Babel will transpile/compile your modern JS code into older (ES5 and below) JS code which can be understood by many browsers. You can use this babel plugin like so.

First, install the babel plugin:

npm install --save-dev @babel/plugin-proposal-class-properties

Then add the plugin to your configuration file:

{
  "plugins": ["@babel/plugin-proposal-class-properties"]
}

For other installation options (babel CLI, etc), see the usage section of the plugin's docs.

like image 149
Nick Parsons Avatar answered Sep 27 '22 21:09

Nick Parsons